lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | agpl-3.0 | 3c69ad32b70a14e4e0d92582377d708f245d24d0 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 6b3d4056-2e60-11e5-9284-b827eb9e62be | hello.java | 6b37de2c-2e60-11e5-9284-b827eb9e62be | 6b3d4056-2e60-11e5-9284-b827eb9e62be | hello.java | 6b3d4056-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>6b37de2c-2e60-11e5-9284-b827eb9e62be
<add>6b3d4056-2e60-11e5-9284-b827eb9e62be |
|
Java | mit | 7d8f439df4cdc10a2e03c3fead3c58939c42fccc | 0 | innovimax/xspec,innovimax/xspec | /****************************************************************************/
/* File: XSLTCoverageTraceListener.java */
/* Author: Jeni Tennison */
/* URI: https://github.com/expath/xspec/ */
/* Tags: */
/* Copyright (c) 2008-2016 (see end of file.) */
/* ------------------------------------------------------------------------ */
package com.jenitennison.xslt.tests;
import net.sf.saxon.lib.TraceListener;
import net.sf.saxon.trace.InstructionInfo;
import net.sf.saxon.trace.LocationKind;
import net.sf.saxon.Controller;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.StandardNames;
import java.lang.String;
import java.util.HashMap;
import java.util.HashSet;
import java.io.PrintStream;
import net.sf.saxon.lib.Logger;
/**
* A Simple trace listener for XSLT that writes messages (by default) to System.err
*/
public class XSLTCoverageTraceListener implements TraceListener {
private PrintStream out = System.err;
private String xspecStylesheet = null;
private String utilsStylesheet = null;
private HashMap<String, Integer> modules = new HashMap<String, Integer>();
private HashSet<Integer> constructs = new HashSet<Integer>();
private int moduleCount = 0;
public XSLTCoverageTraceListener() {
System.out.println("****************************************");
}
/**
* Method called at the start of execution, that is, when the run-time transformation starts
*/
@Override
public void open(Controller c) {
this.out.println("<trace>");
System.out.println("controller="+c);
}
/**
* Method that implements the output destination for SaxonEE/PE 9.7
*/
@Override
public void setOutputDestination(Logger logger) {
// Do nothing
}
/**
* Method called at the end of execution, that is, when the run-time execution ends
*/
@Override
public void close() {
this.out.println("</trace>");
}
/**
* Method that is called when an instruction in the stylesheet gets processed.
* @param instruction gives information about the instruction being
* executed, and about the context in which it is executed. This object is mutable,
* so if information from the InstructionInfo is to be retained, it must be copied.
*/
@Override
public void enter(InstructionInfo info, XPathContext context) {
int lineNumber = info.getLineNumber();
String systemId = info.getSystemId();
int constructType = info.getConstructType();
if (this.utilsStylesheet == null &&
systemId.indexOf("generate-tests-utils.xsl") != -1) {
this.utilsStylesheet = systemId;
this.out.println("<u u=\"" + systemId + "\" />");
} else if (this.xspecStylesheet == null &&
systemId.indexOf("/xspec/") != -1) {
this.xspecStylesheet = systemId;
this.out.println("<x u=\"" + systemId + "\" />");
}
if (systemId != this.xspecStylesheet && systemId != this.utilsStylesheet) {
Integer module;
if (this.modules.containsKey(systemId)) {
module = this.modules.get(systemId);
} else {
module = new Integer(this.moduleCount);
this.moduleCount += 1;
this.modules.put(systemId, module);
this.out.println("<m id=\"" + module + "\" u=\"" + systemId + "\" />");
}
if (!this.constructs.contains(constructType)) {
String construct;
if (constructType < 1024) {
construct = StandardNames.getClarkName(constructType);
} else {
switch (constructType) {
case LocationKind.LITERAL_RESULT_ELEMENT:
construct = "LITERAL_RESULT_ELEMENT";
break;
case LocationKind.LITERAL_RESULT_ATTRIBUTE:
construct = "LITERAL_RESULT_ATTRIBUTE";
break;
case LocationKind.EXTENSION_INSTRUCTION:
construct = "EXTENSION_INSTRUCTION";
break;
case LocationKind.TEMPLATE:
construct = "TEMPLATE";
break;
case LocationKind.FUNCTION_CALL:
construct = "FUNCTION_CALL";
break;
case LocationKind.XPATH_IN_XSLT:
construct = "XPATH_IN_XSLT";
break;
case LocationKind.LET_EXPRESSION:
construct = "LET_EXPRESSION";
break;
case LocationKind.TRACE_CALL:
construct = "TRACE_CALL";
break;
case LocationKind.SAXON_EVALUATE:
construct = "SAXON_EVALUATE";
break;
case LocationKind.FUNCTION:
construct = "FUNCTION";
break;
case LocationKind.XPATH_EXPRESSION:
construct = "XPATH_EXPRESSION";
break;
default:
construct = "Other";
}
}
this.constructs.add(constructType);
this.out.println("<c id=\"" + constructType + "\" n=\"" + construct + "\" />");
}
this.out.println("<h l=\"" + lineNumber + "\" m=\"" + module + "\" c=\"" + constructType + "\" />");
}
}
/**
* Method that is called after processing an instruction of the stylesheet,
* that is, after any child instructions have been processed.
* @param instruction gives the same information that was supplied to the
* enter method, though it is not necessarily the same object. Note that the
* line number of the instruction is that of the start tag in the source stylesheet,
* not the line number of the end tag.
*/
@Override
public void leave(InstructionInfo instruction) {
// Do nothing
}
/**
* Method that is called by an instruction that changes the current item
* in the source document: that is, xsl:for-each, xsl:apply-templates, xsl:for-each-group.
* The method is called after the enter method for the relevant instruction, and is called
* once for each item processed.
* @param currentItem the new current item. Item objects are not mutable; it is safe to retain
* a reference to the Item for later use.
*/
@Override
public void startCurrentItem(Item currentItem) {
// Do nothing
}
/**
* Method that is called when an instruction has finished processing a new current item
* and is ready to select a new current item or revert to the previous current item.
* The method will be called before the leave() method for the instruction that made this
* item current.
* @param currentItem the item that was current, whose processing is now complete. This will represent
* the same underlying item as the corresponding startCurrentItem() call, though it will
* not necessarily be the same actual object.
*/
@Override
public void endCurrentItem(Item currentItem) {
// Do nothing
}
}
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License
// at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is: all this file.
//
// The Initial Developer of the Original Code is Edwin Glaser
// ([email protected])
//
// Portions created by Jeni Tennison are Copyright (C) Jeni Tennison.
// All Rights Reserved.
//
// Contributor(s): Heavily modified by Michael Kay
// Methods implemented by Jeni Tennison
// Extended for Saxon 9.7 by Sandro Cirulli, github.com/cirulls
| java/com/jenitennison/xslt/tests/XSLTCoverageTraceListener.java | /****************************************************************************/
/* File: XSLTCoverageTraceListener.java */
/* Author: Jeni Tennison */
/* URI: https://github.com/expath/xspec/ */
/* Tags: */
/* Copyright (c) 2008-2016 (see end of file.) */
/* ------------------------------------------------------------------------ */
package com.jenitennison.xslt.tests;
import net.sf.saxon.lib.TraceListener;
import net.sf.saxon.trace.InstructionInfo;
import net.sf.saxon.trace.LocationKind;
import net.sf.saxon.Controller;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.StandardNames;
import java.lang.String;
import java.util.HashMap;
import java.util.HashSet;
import java.io.PrintStream;
import net.sf.saxon.lib.Logger;
/**
* A Simple trace listener for XSLT that writes messages (by default) to System.err
*/
public class XSLTCoverageTraceListener implements TraceListener {
private PrintStream out = System.err;
private String xspecStylesheet = null;
private String utilsStylesheet = null;
private HashMap<String, Integer> modules = new HashMap<String, Integer>();
private HashSet<Integer> constructs = new HashSet<Integer>();
private int moduleCount = 0;
public XSLTCoverageTraceListener() {
System.out.println("****************************************");
}
/**
* Method called at the start of execution, that is, when the run-time transformation starts
*/
public void open(Controller c) {
out.println("<trace>");
System.out.println("controller="+c);
}
/**
* Method that implements the output destination for SaxonEE/PE 9.7
*/
public void setOutputDestination(Logger logger) {
}
/**
* Method called at the end of execution, that is, when the run-time execution ends
*/
public void close() {
out.println("</trace>");
}
/**
* Method that is called when an instruction in the stylesheet gets processed.
* @param instruction gives information about the instruction being
* executed, and about the context in which it is executed. This object is mutable,
* so if information from the InstructionInfo is to be retained, it must be copied.
*/
public void enter(InstructionInfo info, XPathContext context) {
int lineNumber = info.getLineNumber();
String systemId = info.getSystemId();
int constructType = info.getConstructType();
if (utilsStylesheet == null &&
systemId.indexOf("generate-tests-utils.xsl") != -1) {
utilsStylesheet = systemId;
out.println("<u u=\"" + systemId + "\" />");
} else if (xspecStylesheet == null &&
systemId.indexOf("/xspec/") != -1) {
xspecStylesheet = systemId;
out.println("<x u=\"" + systemId + "\" />");
}
if (systemId != xspecStylesheet && systemId != utilsStylesheet) {
Integer module;
if (modules.containsKey(systemId)) {
module = (Integer)modules.get(systemId);
} else {
module = new Integer(moduleCount);
moduleCount += 1;
modules.put(systemId, module);
out.println("<m id=\"" + module + "\" u=\"" + systemId + "\" />");
}
if (!constructs.contains(constructType)) {
String construct;
if (constructType < 1024) {
construct = StandardNames.getClarkName(constructType);
} else {
switch (constructType) {
case LocationKind.LITERAL_RESULT_ELEMENT:
construct = "LITERAL_RESULT_ELEMENT";
break;
case LocationKind.LITERAL_RESULT_ATTRIBUTE:
construct = "LITERAL_RESULT_ATTRIBUTE";
break;
case LocationKind.EXTENSION_INSTRUCTION:
construct = "EXTENSION_INSTRUCTION";
break;
case LocationKind.TEMPLATE:
construct = "TEMPLATE";
break;
case LocationKind.FUNCTION_CALL:
construct = "FUNCTION_CALL";
break;
case LocationKind.XPATH_IN_XSLT:
construct = "XPATH_IN_XSLT";
break;
case LocationKind.LET_EXPRESSION:
construct = "LET_EXPRESSION";
break;
case LocationKind.TRACE_CALL:
construct = "TRACE_CALL";
break;
case LocationKind.SAXON_EVALUATE:
construct = "SAXON_EVALUATE";
break;
case LocationKind.FUNCTION:
construct = "FUNCTION";
break;
case LocationKind.XPATH_EXPRESSION:
construct = "XPATH_EXPRESSION";
break;
default:
construct = "Other";
}
}
constructs.add(constructType);
out.println("<c id=\"" + constructType + "\" n=\"" + construct + "\" />");
}
out.println("<h l=\"" + lineNumber + "\" m=\"" + module + "\" c=\"" + constructType + "\" />");
}
}
/**
* Method that is called after processing an instruction of the stylesheet,
* that is, after any child instructions have been processed.
* @param instruction gives the same information that was supplied to the
* enter method, though it is not necessarily the same object. Note that the
* line number of the instruction is that of the start tag in the source stylesheet,
* not the line number of the end tag.
*/
public void leave(InstructionInfo instruction) {
// Do nothing
}
/**
* Method that is called by an instruction that changes the current item
* in the source document: that is, xsl:for-each, xsl:apply-templates, xsl:for-each-group.
* The method is called after the enter method for the relevant instruction, and is called
* once for each item processed.
* @param currentItem the new current item. Item objects are not mutable; it is safe to retain
* a reference to the Item for later use.
*/
public void startCurrentItem(Item currentItem) {
// Do nothing
}
/**
* Method that is called when an instruction has finished processing a new current item
* and is ready to select a new current item or revert to the previous current item.
* The method will be called before the leave() method for the instruction that made this
* item current.
* @param currentItem the item that was current, whose processing is now complete. This will represent
* the same underlying item as the corresponding startCurrentItem() call, though it will
* not necessarily be the same actual object.
*/
public void endCurrentItem(Item currentItem) {
// Do nothing
}
}
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License
// at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is: all this file.
//
// The Initial Developer of the Original Code is Edwin Glaser
// ([email protected])
//
// Portions created by Jeni Tennison are Copyright (C) Jeni Tennison.
// All Rights Reserved.
//
// Contributor(s): Heavily modified by Michael Kay
// Methods implemented by Jeni Tennison
// Extended for Saxon 9.7 by Sandro Cirulli, github.com/cirulls
| add @Override, add this., remove extra casting
comment empty block | java/com/jenitennison/xslt/tests/XSLTCoverageTraceListener.java | add @Override, add this., remove extra casting | <ide><path>ava/com/jenitennison/xslt/tests/XSLTCoverageTraceListener.java
<ide> /**
<ide> * Method called at the start of execution, that is, when the run-time transformation starts
<ide> */
<del>
<add> @Override
<ide> public void open(Controller c) {
<del> out.println("<trace>");
<add> this.out.println("<trace>");
<ide> System.out.println("controller="+c);
<ide> }
<ide>
<ide> /**
<ide> * Method that implements the output destination for SaxonEE/PE 9.7
<ide> */
<add> @Override
<ide> public void setOutputDestination(Logger logger) {
<add> // Do nothing
<ide> }
<ide>
<ide> /**
<ide> * Method called at the end of execution, that is, when the run-time execution ends
<ide> */
<del>
<add> @Override
<ide> public void close() {
<del> out.println("</trace>");
<add> this.out.println("</trace>");
<ide> }
<ide>
<ide> /**
<ide> * executed, and about the context in which it is executed. This object is mutable,
<ide> * so if information from the InstructionInfo is to be retained, it must be copied.
<ide> */
<del>
<add> @Override
<ide> public void enter(InstructionInfo info, XPathContext context) {
<ide> int lineNumber = info.getLineNumber();
<ide> String systemId = info.getSystemId();
<ide> int constructType = info.getConstructType();
<del> if (utilsStylesheet == null &&
<add> if (this.utilsStylesheet == null &&
<ide> systemId.indexOf("generate-tests-utils.xsl") != -1) {
<del> utilsStylesheet = systemId;
<del> out.println("<u u=\"" + systemId + "\" />");
<del> } else if (xspecStylesheet == null &&
<add> this.utilsStylesheet = systemId;
<add> this.out.println("<u u=\"" + systemId + "\" />");
<add> } else if (this.xspecStylesheet == null &&
<ide> systemId.indexOf("/xspec/") != -1) {
<del> xspecStylesheet = systemId;
<del> out.println("<x u=\"" + systemId + "\" />");
<add> this.xspecStylesheet = systemId;
<add> this.out.println("<x u=\"" + systemId + "\" />");
<ide> }
<del> if (systemId != xspecStylesheet && systemId != utilsStylesheet) {
<add> if (systemId != this.xspecStylesheet && systemId != this.utilsStylesheet) {
<ide> Integer module;
<del> if (modules.containsKey(systemId)) {
<del> module = (Integer)modules.get(systemId);
<add> if (this.modules.containsKey(systemId)) {
<add> module = this.modules.get(systemId);
<ide> } else {
<del> module = new Integer(moduleCount);
<del> moduleCount += 1;
<del> modules.put(systemId, module);
<del> out.println("<m id=\"" + module + "\" u=\"" + systemId + "\" />");
<add> module = new Integer(this.moduleCount);
<add> this.moduleCount += 1;
<add> this.modules.put(systemId, module);
<add> this.out.println("<m id=\"" + module + "\" u=\"" + systemId + "\" />");
<ide> }
<del> if (!constructs.contains(constructType)) {
<add> if (!this.constructs.contains(constructType)) {
<ide> String construct;
<ide> if (constructType < 1024) {
<ide> construct = StandardNames.getClarkName(constructType);
<ide> construct = "Other";
<ide> }
<ide> }
<del> constructs.add(constructType);
<del> out.println("<c id=\"" + constructType + "\" n=\"" + construct + "\" />");
<add> this.constructs.add(constructType);
<add> this.out.println("<c id=\"" + constructType + "\" n=\"" + construct + "\" />");
<ide> }
<del> out.println("<h l=\"" + lineNumber + "\" m=\"" + module + "\" c=\"" + constructType + "\" />");
<add> this.out.println("<h l=\"" + lineNumber + "\" m=\"" + module + "\" c=\"" + constructType + "\" />");
<ide> }
<ide> }
<ide>
<ide> * line number of the instruction is that of the start tag in the source stylesheet,
<ide> * not the line number of the end tag.
<ide> */
<del>
<add> @Override
<ide> public void leave(InstructionInfo instruction) {
<ide> // Do nothing
<ide> }
<ide> * @param currentItem the new current item. Item objects are not mutable; it is safe to retain
<ide> * a reference to the Item for later use.
<ide> */
<del>
<add> @Override
<ide> public void startCurrentItem(Item currentItem) {
<ide> // Do nothing
<ide> }
<ide> * the same underlying item as the corresponding startCurrentItem() call, though it will
<ide> * not necessarily be the same actual object.
<ide> */
<del>
<add> @Override
<ide> public void endCurrentItem(Item currentItem) {
<ide> // Do nothing
<ide> } |
|
Java | mit | 296983dc63d89ee3569a0a7a32b23d51bbfcc4ad | 0 | drmercer/PickerForUnsplashPhotos | package net.danmercer.unsplashpicker;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import net.danmercer.unsplashpicker.data.PhotoInfo;
import net.danmercer.unsplashpicker.util.UnsplashApiUtils;
import net.danmercer.unsplashpicker.util.UnsplashQuery;
import net.danmercer.unsplashpicker.view.ImageQueryAdapter;
import net.danmercer.unsplashpicker.view.ImageRecyclerView;
/**
* The main picker activity.
*
* @author Dan Mercer
*/
public class ImagePickActivity extends AppCompatActivity {
static final String EXTRA_PHOTO_ID = "net.danmercer.unsplashpicker.PHOTO_ID";
private ImageQueryAdapter adapter;
private UnsplashQuery query;
private SearchView searchView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String appID = UnsplashApiUtils.getApiKey(this);
ImageRecyclerView view = new ImageRecyclerView(this);
adapter = new ImageQueryAdapter(this);
view.setAdapter(adapter);
final GridLayoutManager layoutManager = getLayoutManager();
view.setLayoutManager(layoutManager);
query = initQuery(appID);
adapter.updateQuery(query);
// Listen for scroll to the end, and load more photos
view.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
final int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
final int itemCount = adapter.getItemCount();
if (lastVisibleItemPosition+1 >= itemCount && !query.isLoading()) {
// Scroll has reached the end, load another page (but not in the scroll
// listener, because that causes bugs when notify*() is called on the
// recyclerView).
recyclerView.post(new Runnable() {
@Override
public void run() {
query.nextPage();
adapter.updateQuery(query);
}
});
}
}
});
// Set up item click listener
adapter.setOnPhotoChosenListener(new ImageQueryAdapter.OnPhotoChosenListener() {
@Override
public void onPhotoChosen(PhotoInfo choice) {
final Intent result = new Intent();
result.putExtra(EXTRA_PHOTO_ID, choice.id);
setResult(RESULT_OK, result);
finish();
}
});
setContentView(view);
}
/**
* Called by {@link #onCreate(Bundle)} to get a layout manager for the recycler view. The
* default implementation returns a GridLayoutManager with 2 spans per row. Override this method
* to tweak the LayoutManager.
*
* @return The GridLayoutManager to use.
*/
@NonNull
protected GridLayoutManager getLayoutManager() {
final GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (adapter.getItemViewType(position) == ImageQueryAdapter.TYPE_IMAGE) {
return 1;
} else {
return 2;
}
}
});
return layoutManager;
}
/**
* Called to initialze the UnsplashQuery object that is used to show photos. The default
* implementation just returns <code>new UnsplashQuery(appID)</code>, which just loads curated
* photos 20 at a time. Override this to modify the initial state of the query.
*
* @param appID
* The app ID. Pass this to the {@link UnsplashQuery#UnsplashQuery(String)}
* constructor.
* @return
* The new UnsplashQuery object.
*/
@NonNull
protected UnsplashQuery initQuery(String appID) {
return new UnsplashQuery(appID);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.uip_picker, menu);
// Set up search:
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.uip_action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
onSearchSubmitted(text);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
onSearchTextChanged(newText);
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
onSearchClosed();
return false;
}
});
return true;
}
/**
* Called whenever the search text changes (e.g. as the user types). The default implementation
* does nothing - the user must submit the search for anything to happen - but if you want to
* show results instantly then just call {@link #onSearchSubmitted(String)} from this method.
*
* @param text
* The current text in the search field.
*/
protected void onSearchTextChanged(String text) { /* Does nothing by default */ }
/**
* Called whenever a search query is submitted by the user. The default implementation performs
* the search by updating the current query.
* @param text
* The search string.
*/
protected void onSearchSubmitted(String text) {
query.setSearch(text);
adapter.updateQuery(query);
}
/**
* Called whenever the search UI is closed (whether by the user or programmatically). The
* default implementation cancels the search by calling {@link UnsplashQuery#cancelSearch()}
* on the query.
*/
protected void onSearchClosed() {
query.cancelSearch();
adapter.updateQuery(query);
}
/**
* Hides the search UI.
*
* @return true if the search was active, false if not (and nothing was done).
*/
protected boolean cancelSearch() {
if (searchView != null && !searchView.isIconified()) {
// Empty the query:
searchView.setQuery("", false);
// Close the search view:
searchView.setIconified(true);
return true;
} else {
return false;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == R.id.uip_action_about) {
// Show About dialog:
AlertDialog.Builder db = new AlertDialog.Builder(this);
db.setTitle(R.string.uip_about_title);
final TextView msg = (TextView) getLayoutInflater().inflate(R.layout.uip_about, null);
final String unsplashAttribUrl = UnsplashApiUtils.getUnsplashAttribUrl(this);
//noinspection deprecation (Non-deprecated fromHtml() requires Android N.)
msg.setText(Html.fromHtml(getString(R.string.uip_about, unsplashAttribUrl)));
msg.setMovementMethod(LinkMovementMethod.getInstance());
db.setView(msg);
db.setPositiveButton(android.R.string.ok, null);
db.show();
return true;
} else if (id == android.R.id.home) {
// If Up button is pressed while the Search UI is shown, hide it. (Otherwise, proceed as
// normal.)
if (cancelSearch()) {
return true;
}
}
return super.onOptionsItemSelected(item);
}
/**
* If the Search UI is shown, hides it. Otherwise, does the normal back button behavior.
*/
@Override
public void onBackPressed() {
// Only actually go back if the Search UI isn't shown. If it is, just hide it.
if (!cancelSearch()) {
super.onBackPressed();
}
}
}
| library/src/main/java/net/danmercer/unsplashpicker/ImagePickActivity.java | package net.danmercer.unsplashpicker;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import net.danmercer.unsplashpicker.data.PhotoInfo;
import net.danmercer.unsplashpicker.util.UnsplashApiUtils;
import net.danmercer.unsplashpicker.util.UnsplashQuery;
import net.danmercer.unsplashpicker.view.ImageQueryAdapter;
import net.danmercer.unsplashpicker.view.ImageRecyclerView;
/**
* The main picker activity.
*
* @author Dan Mercer
*/
public class ImagePickActivity extends AppCompatActivity {
static final String EXTRA_PHOTO_ID = "net.danmercer.unsplashpicker.PHOTO_ID";
private ImageQueryAdapter adapter;
private UnsplashQuery query;
private SearchView searchView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String appID = UnsplashApiUtils.getApiKey(this);
ImageRecyclerView view = new ImageRecyclerView(this);
adapter = new ImageQueryAdapter(this);
view.setAdapter(adapter);
final GridLayoutManager layoutManager = getLayoutManager();
view.setLayoutManager(layoutManager);
query = initQuery(appID);
adapter.updateQuery(query);
// Listen for scroll to the end, and load more photos
view.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
final int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
final int itemCount = adapter.getItemCount();
if (lastVisibleItemPosition+1 >= itemCount && !query.isLoading()) {
// Scroll has reached the end, load another page
query.nextPage();
adapter.updateQuery(query);
}
}
});
// Set up item click listener
adapter.setOnPhotoChosenListener(new ImageQueryAdapter.OnPhotoChosenListener() {
@Override
public void onPhotoChosen(PhotoInfo choice) {
final Intent result = new Intent();
result.putExtra(EXTRA_PHOTO_ID, choice.id);
setResult(RESULT_OK, result);
finish();
}
});
setContentView(view);
}
/**
* Called by {@link #onCreate(Bundle)} to get a layout manager for the recycler view. The
* default implementation returns a GridLayoutManager with 2 spans per row. Override this method
* to tweak the LayoutManager.
*
* @return The GridLayoutManager to use.
*/
@NonNull
protected GridLayoutManager getLayoutManager() {
final GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (adapter.getItemViewType(position) == ImageQueryAdapter.TYPE_IMAGE) {
return 1;
} else {
return 2;
}
}
});
return layoutManager;
}
/**
* Called to initialze the UnsplashQuery object that is used to show photos. The default
* implementation just returns <code>new UnsplashQuery(appID)</code>, which just loads curated
* photos 20 at a time. Override this to modify the initial state of the query.
*
* @param appID
* The app ID. Pass this to the {@link UnsplashQuery#UnsplashQuery(String)}
* constructor.
* @return
* The new UnsplashQuery object.
*/
@NonNull
protected UnsplashQuery initQuery(String appID) {
return new UnsplashQuery(appID);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.uip_picker, menu);
// Set up search:
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.uip_action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
onSearchSubmitted(text);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
onSearchTextChanged(newText);
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
onSearchClosed();
return false;
}
});
return true;
}
/**
* Called whenever the search text changes (e.g. as the user types). The default implementation
* does nothing - the user must submit the search for anything to happen - but if you want to
* show results instantly then just call {@link #onSearchSubmitted(String)} from this method.
*
* @param text
* The current text in the search field.
*/
protected void onSearchTextChanged(String text) { /* Does nothing by default */ }
/**
* Called whenever a search query is submitted by the user. The default implementation performs
* the search by updating the current query.
* @param text
* The search string.
*/
protected void onSearchSubmitted(String text) {
query.setSearch(text);
adapter.updateQuery(query);
}
/**
* Called whenever the search UI is closed (whether by the user or programmatically). The
* default implementation cancels the search by calling {@link UnsplashQuery#cancelSearch()}
* on the query.
*/
protected void onSearchClosed() {
query.cancelSearch();
adapter.updateQuery(query);
}
/**
* Hides the search UI.
*
* @return true if the search was active, false if not (and nothing was done).
*/
protected boolean cancelSearch() {
if (searchView != null && !searchView.isIconified()) {
// Empty the query:
searchView.setQuery("", false);
// Close the search view:
searchView.setIconified(true);
return true;
} else {
return false;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == R.id.uip_action_about) {
// Show About dialog:
AlertDialog.Builder db = new AlertDialog.Builder(this);
db.setTitle(R.string.uip_about_title);
final TextView msg = (TextView) getLayoutInflater().inflate(R.layout.uip_about, null);
final String unsplashAttribUrl = UnsplashApiUtils.getUnsplashAttribUrl(this);
//noinspection deprecation (Non-deprecated fromHtml() requires Android N.)
msg.setText(Html.fromHtml(getString(R.string.uip_about, unsplashAttribUrl)));
msg.setMovementMethod(LinkMovementMethod.getInstance());
db.setView(msg);
db.setPositiveButton(android.R.string.ok, null);
db.show();
return true;
} else if (id == android.R.id.home) {
// If Up button is pressed while the Search UI is shown, hide it. (Otherwise, proceed as
// normal.)
if (cancelSearch()) {
return true;
}
}
return super.onOptionsItemSelected(item);
}
/**
* If the Search UI is shown, hides it. Otherwise, does the normal back button behavior.
*/
@Override
public void onBackPressed() {
// Only actually go back if the Search UI isn't shown. If it is, just hide it.
if (!cancelSearch()) {
super.onBackPressed();
}
}
}
| Bugfix in IPA.
Apparently calling notify*() on a RecyclerView is disallowed in a scroll callback, because
"Scroll callbacks mightbe run during a measure & layout pass where you cannot change
theRecyclerView data." (That's from the error message.)
| library/src/main/java/net/danmercer/unsplashpicker/ImagePickActivity.java | Bugfix in IPA. | <ide><path>ibrary/src/main/java/net/danmercer/unsplashpicker/ImagePickActivity.java
<ide> final int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
<ide> final int itemCount = adapter.getItemCount();
<ide> if (lastVisibleItemPosition+1 >= itemCount && !query.isLoading()) {
<del> // Scroll has reached the end, load another page
<del> query.nextPage();
<del> adapter.updateQuery(query);
<add> // Scroll has reached the end, load another page (but not in the scroll
<add> // listener, because that causes bugs when notify*() is called on the
<add> // recyclerView).
<add> recyclerView.post(new Runnable() {
<add> @Override
<add> public void run() {
<add> query.nextPage();
<add> adapter.updateQuery(query);
<add> }
<add> });
<ide> }
<ide> }
<ide> }); |
|
Java | mit | 6591c1d4745935197c3dd125eeb43d0beccbf83e | 0 | Nincodedo/Ninbot | package com.nincraft.ninbot.components.twitch;
import com.nincraft.ninbot.components.common.MessageUtils;
import com.nincraft.ninbot.components.config.ConfigConstants;
import com.nincraft.ninbot.components.config.ConfigService;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import net.dv8tion.jda.core.events.user.update.GenericUserPresenceEvent;
import net.dv8tion.jda.core.events.user.update.UserUpdateGameEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import org.springframework.stereotype.Component;
@Component
@Log4j2
public class TwitchListener extends ListenerAdapter {
private ConfigService configService;
private MessageUtils messageUtils;
public TwitchListener(ConfigService configService, MessageUtils messageUtils) {
this.configService = configService;
this.messageUtils = messageUtils;
}
@Override
public void onGenericUserPresence(GenericUserPresenceEvent event) {
if (event instanceof UserUpdateGameEvent) {
val updateGameEvent = (UserUpdateGameEvent) event;
log.debug("UserUpdateEvent " + updateGameEvent);
log.debug("Old game " + updateGameEvent.getOldGame());
log.debug("New game " + updateGameEvent.getNewGame());
if (updateGameEvent.getOldGame() != null && updateGameEvent.getNewGame() != null
&& updateGameEvent.getOldGame().getUrl() == null && updateGameEvent.getNewGame().getUrl() != null) {
val serverId = event.getGuild().getId();
val streamingAnnounceUsers = configService.getValuesByName(serverId, ConfigConstants.STREAMING_ANNOUNCE_USERS);
if (streamingAnnounceUsers.contains(event.getMember().getUser().getId())) {
val streamingAnnounceChannel = configService.getSingleValueByName(serverId, ConfigConstants.STREAMING_ANNOUNCE_CHANNEL);
if (streamingAnnounceChannel.isPresent()) {
val channel = event.getGuild().getTextChannelById(streamingAnnounceChannel.get());
val user = updateGameEvent.getUser().getName();
val url = updateGameEvent.getNewGame().getUrl();
messageUtils.sendMessage(channel, "%s is streaming! Check them out at %s", user, url);
}
}
}
}
}
}
| src/main/java/com/nincraft/ninbot/components/twitch/TwitchListener.java | package com.nincraft.ninbot.components.twitch;
import com.nincraft.ninbot.components.common.MessageUtils;
import com.nincraft.ninbot.components.config.ConfigConstants;
import com.nincraft.ninbot.components.config.ConfigService;
import lombok.val;
import net.dv8tion.jda.core.events.user.update.GenericUserPresenceEvent;
import net.dv8tion.jda.core.events.user.update.UserUpdateGameEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import org.springframework.stereotype.Component;
@Component
public class TwitchListener extends ListenerAdapter {
private ConfigService configService;
private MessageUtils messageUtils;
public TwitchListener(ConfigService configService, MessageUtils messageUtils) {
this.configService = configService;
this.messageUtils = messageUtils;
}
@Override
public void onGenericUserPresence(GenericUserPresenceEvent event) {
if (event instanceof UserUpdateGameEvent) {
val updateGameEvent = (UserUpdateGameEvent) event;
if (updateGameEvent.getOldGame() != null && updateGameEvent.getNewGame() != null
&& updateGameEvent.getOldGame().getUrl() == null && updateGameEvent.getNewGame().getUrl() != null) {
val serverId = event.getGuild().getId();
val streamingAnnounceUsers = configService.getValuesByName(serverId, ConfigConstants.STREAMING_ANNOUNCE_USERS);
if (streamingAnnounceUsers.contains(event.getMember().getUser().getId())) {
val streamingAnnounceChannel = configService.getSingleValueByName(serverId, ConfigConstants.STREAMING_ANNOUNCE_CHANNEL);
if (streamingAnnounceChannel.isPresent()) {
val channel = event.getGuild().getTextChannelById(streamingAnnounceChannel.get());
val user = updateGameEvent.getUser().getName();
val url = updateGameEvent.getNewGame().getUrl();
messageUtils.sendMessage(channel, "%s is streaming! Check them out at %s", user, url);
}
}
}
}
}
}
| Add logging to Twitch listener
| src/main/java/com/nincraft/ninbot/components/twitch/TwitchListener.java | Add logging to Twitch listener | <ide><path>rc/main/java/com/nincraft/ninbot/components/twitch/TwitchListener.java
<ide> import com.nincraft.ninbot.components.common.MessageUtils;
<ide> import com.nincraft.ninbot.components.config.ConfigConstants;
<ide> import com.nincraft.ninbot.components.config.ConfigService;
<add>import lombok.extern.log4j.Log4j2;
<ide> import lombok.val;
<ide> import net.dv8tion.jda.core.events.user.update.GenericUserPresenceEvent;
<ide> import net.dv8tion.jda.core.events.user.update.UserUpdateGameEvent;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> @Component
<add>@Log4j2
<ide> public class TwitchListener extends ListenerAdapter {
<ide>
<ide> private ConfigService configService;
<ide> public void onGenericUserPresence(GenericUserPresenceEvent event) {
<ide> if (event instanceof UserUpdateGameEvent) {
<ide> val updateGameEvent = (UserUpdateGameEvent) event;
<add> log.debug("UserUpdateEvent " + updateGameEvent);
<add> log.debug("Old game " + updateGameEvent.getOldGame());
<add> log.debug("New game " + updateGameEvent.getNewGame());
<ide> if (updateGameEvent.getOldGame() != null && updateGameEvent.getNewGame() != null
<ide> && updateGameEvent.getOldGame().getUrl() == null && updateGameEvent.getNewGame().getUrl() != null) {
<ide> val serverId = event.getGuild().getId(); |
|
JavaScript | apache-2.0 | 018367e2a8dac45c698879d0ff37d9906e33d35d | 0 | scality/S3,scality/S3,tomateos/S3,truststamp/S3,scality/S3,lucisilv/Silviu_S3-Antidote,tomateos/S3,tomateos/S3,tomateos/S3,scality/S3,truststamp/S3,truststamp/S3,truststamp/S3,truststamp/S3,lucisilv/Silviu_S3-Antidote,truststamp/S3,truststamp/S3,tomateos/S3,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,truststamp/S3,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,tomateos/S3,scality/S3,tomateos/S3,scality/S3,scality/S3,tomateos/S3,scality/S3 | import assert from 'assert';
import Promise from 'bluebird';
import withV4 from '../support/withV4';
import BucketUtility from '../../lib/utility/bucket-util';
describe('PUT Object ACL', () => {
withV4(sigCfg => {
let bucketUtil;
let bucketName;
before(done => {
bucketUtil = new BucketUtility('default', sigCfg);
bucketUtil.createRandom(1)
.catch(done)
.then(created => {
bucketName = created;
done();
});
});
after(done => {
bucketUtil.deleteOne(bucketName).then(() => done()).catch(done);
});
afterEach(done => {
bucketUtil.empty(bucketName).catch(done).done(() => done());
});
it('should put object ACLs', done => {
const s3 = bucketUtil.s3;
const Bucket = bucketName;
const Key = 'aclTest';
const objects = [
{ Bucket, Key },
];
Promise
.mapSeries(objects, param => s3.putObjectAsync(param))
.then(() => s3.putObjectAclAsync({ Bucket, Key,
ACL: 'public-read' }))
.then(data => {
assert(data);
done();
}).catch(done);
});
it('should return NoSuchKey if try to put object ACLs ' +
'for nonexistent object', done => {
const s3 = bucketUtil.s3;
const Bucket = bucketName;
const Key = 'aclTest';
s3.putObjectAcl({
Bucket,
Key,
ACL: 'public-read' }, err => {
assert(err);
assert.strictEqual(err.statusCode, 404);
assert.strictEqual(err.code, 'NoSuchKey');
done();
});
});
});
});
| tests/functional/aws-node-sdk/test/object/putObjAcl.js | import assert from 'assert';
import Promise from 'bluebird';
import withV4 from '../support/withV4';
import BucketUtility from '../../lib/utility/bucket-util';
describe.only('PUT Object ACL', () => {
withV4(sigCfg => {
let bucketUtil;
let bucketName;
before(done => {
bucketUtil = new BucketUtility('default', sigCfg);
bucketUtil.createRandom(1)
.catch(done)
.then(created => {
bucketName = created;
done();
});
});
after(done => {
bucketUtil.deleteOne(bucketName).then(() => done()).catch(done);
});
afterEach(done => {
bucketUtil.empty(bucketName).catch(done).done(() => done());
});
it('should put object ACLs', done => {
const s3 = bucketUtil.s3;
const Bucket = bucketName;
const Key = 'aclTest';
const objects = [
{ Bucket, Key },
];
Promise
.mapSeries(objects, param => s3.putObjectAsync(param))
.then(() => s3.putObjectAclAsync({ Bucket, Key,
ACL: 'public-read' }))
.then(data => {
assert(data);
done();
}).catch(done);
});
it('should return NoSuchKey if try to put object ACLs ' +
'for nonexistent object', done => {
const s3 = bucketUtil.s3;
const Bucket = bucketName;
const Key = 'aclTest';
s3.putObjectAcl({
Bucket,
Key,
ACL: 'public-read' }, err => {
assert(err);
assert.strictEqual(err.statusCode, 404);
assert.strictEqual(err.code, 'NoSuchKey');
done();
});
});
});
});
| [TESTS](fix): Enable all aws tests
Remove .only() from putObjAcl tests to activate all aws
tests
| tests/functional/aws-node-sdk/test/object/putObjAcl.js | [TESTS](fix): Enable all aws tests | <ide><path>ests/functional/aws-node-sdk/test/object/putObjAcl.js
<ide> import withV4 from '../support/withV4';
<ide> import BucketUtility from '../../lib/utility/bucket-util';
<ide>
<del>describe.only('PUT Object ACL', () => {
<add>describe('PUT Object ACL', () => {
<ide> withV4(sigCfg => {
<ide> let bucketUtil;
<ide> let bucketName; |
|
Java | mit | 591bfd6b0d74c58397fef43c99524cdb285b8603 | 0 | preipke/petrisim | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.unibi.agbi.petrinet.model;
import edu.unibi.agbi.petrinet.entity.IPN_Arc;
import edu.unibi.agbi.petrinet.entity.IPN_Node;
import edu.unibi.agbi.petrinet.entity.impl.Place;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author PR
*/
public class PetriNet
{
private String author;
private String name;
private String description;
private final List<Colour> colors; // TODO replace by list
private final Map<String,IPN_Arc> arcs;
private final Map<String,IPN_Node> places;
private final Map<String,IPN_Node> transitions;
private final Map<String,IPN_Node> placesAndTransitions; // TODO remove if places and transitions can have the same names
public PetriNet() {
colors = new ArrayList();
arcs = new HashMap();
places = new HashMap();
transitions = new HashMap();
placesAndTransitions = new HashMap();
}
public boolean add(Colour color) {
if (colors.contains(color)) {
return false;
}
colors.add(color);
return true;
}
public boolean add(IPN_Arc arc) {
if (arcs.containsKey(arc.getId())) {
return false;
}
arcs.put(arc.getId(), arc);
return true;
}
public boolean add(IPN_Node node) {
if (placesAndTransitions.containsKey(node.getId())) {
return false;
}
placesAndTransitions.put(node.getId(), node);
if (node instanceof Place) {
places.put(node.getId(), node);
} else {
transitions.put(node.getId(), node);
}
return true;
}
public Collection<IPN_Arc> getArcs() {
return arcs.values();
}
public List<Colour> getColours() {
return colors;
}
public Collection<IPN_Node> getPlaces() {
return places.values();
}
public Collection<IPN_Node> getPlacesAndTransitions() {
return placesAndTransitions.values();
}
public Collection<IPN_Node> getTransitions() {
return transitions.values();
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| PetriNet/src/main/java/edu/unibi/agbi/petrinet/model/PetriNet.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.unibi.agbi.petrinet.model;
import edu.unibi.agbi.petrinet.entity.IPN_Arc;
import edu.unibi.agbi.petrinet.entity.IPN_Node;
import edu.unibi.agbi.petrinet.entity.impl.Place;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author PR
*/
public class PetriNet
{
private String author;
private String name;
private String description;
private final Map<String,IPN_Arc> arcs;
private final Map<String,Colour> colours;
// TODO remove some of the following, depending on if place id can be the same as transition id or not
private final Map<String,IPN_Node> places;
private final Map<String,IPN_Node> transitions;
private final Map<String,IPN_Node> placesAndTransitions;
public PetriNet() {
arcs = new HashMap();
colours = new HashMap();
places = new HashMap();
transitions = new HashMap();
placesAndTransitions = new HashMap();
}
public boolean add(Colour colour) {
if (colours.containsKey(colour.getId())) {
return false;
}
colours.put(colour.getId(), colour);
return true;
}
public boolean add(IPN_Arc arc) {
if (arcs.containsKey(arc.getId())) {
return false;
}
arcs.put(arc.getId(), arc);
return true;
}
public boolean add(IPN_Node node) {
if (placesAndTransitions.containsKey(node.getId())) {
return false;
}
placesAndTransitions.put(node.getId(), node);
if (node instanceof Place) {
places.put(node.getId(), node);
} else {
transitions.put(node.getId(), node);
}
return true;
}
public Collection<IPN_Arc> getArcs() {
return arcs.values();
}
public Collection<Colour> getColours() {
return colours.values();
}
public Collection<IPN_Node> getPlaces() {
return places.values();
}
public Collection<IPN_Node> getPlacesAndTransitions() {
return placesAndTransitions.values();
}
public Collection<IPN_Node> getTransitions() {
return transitions.values();
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| replaced color map by list
| PetriNet/src/main/java/edu/unibi/agbi/petrinet/model/PetriNet.java | replaced color map by list | <ide><path>etriNet/src/main/java/edu/unibi/agbi/petrinet/model/PetriNet.java
<ide> import edu.unibi.agbi.petrinet.entity.IPN_Arc;
<ide> import edu.unibi.agbi.petrinet.entity.IPN_Node;
<ide> import edu.unibi.agbi.petrinet.entity.impl.Place;
<add>import java.util.ArrayList;
<ide>
<ide> import java.util.Collection;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> /**
<ide> private String name;
<ide> private String description;
<ide>
<add> private final List<Colour> colors; // TODO replace by list
<add>
<ide> private final Map<String,IPN_Arc> arcs;
<del> private final Map<String,Colour> colours;
<del> // TODO remove some of the following, depending on if place id can be the same as transition id or not
<ide> private final Map<String,IPN_Node> places;
<ide> private final Map<String,IPN_Node> transitions;
<del> private final Map<String,IPN_Node> placesAndTransitions;
<add> private final Map<String,IPN_Node> placesAndTransitions; // TODO remove if places and transitions can have the same names
<ide>
<ide> public PetriNet() {
<add> colors = new ArrayList();
<ide> arcs = new HashMap();
<del> colours = new HashMap();
<ide> places = new HashMap();
<ide> transitions = new HashMap();
<ide> placesAndTransitions = new HashMap();
<ide> }
<ide>
<del> public boolean add(Colour colour) {
<del> if (colours.containsKey(colour.getId())) {
<add> public boolean add(Colour color) {
<add> if (colors.contains(color)) {
<ide> return false;
<ide> }
<del> colours.put(colour.getId(), colour);
<add> colors.add(color);
<ide> return true;
<ide> }
<ide>
<ide> return arcs.values();
<ide> }
<ide>
<del> public Collection<Colour> getColours() {
<del> return colours.values();
<add> public List<Colour> getColours() {
<add> return colors;
<ide> }
<ide>
<ide> public Collection<IPN_Node> getPlaces() { |
|
JavaScript | unknown | 54e319d03fcdb8bfc959e0aaff3ae4db1ceece47 | 0 | dbaba/candy-red,dbaba/candy-red,CANDY-LINE/candy-red,dbaba/candy-red,CANDY-LINE/candy-red,CANDY-LINE/candy-red | 'use strict';
import WebSocket from 'ws';
import urllib from 'url';
export default function(RED) {
class WebSocketListener {
constructor(accountConfig, account, path, webSocketListeners, options) {
this.accountConfig = accountConfig;
this.account = account;
this.path = path;
this.webSocketListeners = webSocketListeners;
this._inputNodes = []; // collection of thats that want to receive events
this._outputNodes = []; // node status event listeners
this._clients = {};
this.closing = false;
this.options = options || {};
this.startconn(); // start outbound connection
this.redirect = 0;
this.authRetry = 0;
}
startconn(url) { // Connect to remote endpoint
let conf = this.accountConfig;
let prefix = 'ws' + (conf.secure ? 's' : '') + '://';
prefix += conf.loginUser + ':' + conf.loginPassword + '@';
let accountId = conf.accountFqn.split('@');
prefix += accountId[1];
let path = this.path;
if (url) {
let urlobj = urllib.parse(url);
if (!urlobj.host) {
path = urlobj.href;
} else {
prefix = urlobj.href;
path = null;
}
} else {
prefix += '/' + accountId[0] + '/api';
}
if (path && path.length > 0 && path.charAt(0) !== '/') {
prefix += '/';
}
if (path) {
prefix += path;
}
let socket = new WebSocket(prefix, this.options);
this.server = socket; // keep for closing
this.handleConnection(socket);
}
handleConnection(/*socket*/socket) {
let that = this;
let id = (1+Math.random()*4294967295).toString(16);
socket.on('open', () => {
that.emit2all('opened');
that.redirect = 0;
});
socket.on('close', () => {
that.emit2all('closed');
if (!that.closing) {
// try to reconnect every 3+ secs
that.tout = setTimeout(() => { that.startconn(); }, 3000 + Math.random() * 1000);
}
});
socket.on('message', (data,flags) => {
that.handleEvent(id,socket,'message',data,flags);
});
socket.on('unexpected-response', (req, res) => {
that.emit2all('erro');
req.abort();
res.socket.end();
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
if (res.headers.location) {
if (this.redirect > 3) {
this.redirect = 0;
RED.log.error(RED._('candy-egg-ws.errors.too-many-redirects', { path: that.path, location: res.headers.location }));
} else {
++this.redirect;
return this.startconn(res.headers.location);
}
}
} else if (res.statusCode === 404) {
RED.log.error(RED._('candy-egg-ws.errors.wrong-path', { path: that.path }));
} else if (res.statusCode === 401) {
RED.log.error(RED._('candy-egg-ws.errors.auth-error', { path: that.path, user: this.accountConfig.loginUser }));
return; // never retry
} else {
RED.log.error(RED._('candy-egg-ws.errors.server-error', { path: that.path, status: res.statusCode }));
}
// try to reconnect every approx. 1 min
that.tout = setTimeout(() => { that.startconn(); }, 55000 + Math.random() * 10000);
this.redirect = 0;
});
socket.on('error', err => {
that.emit2all('erro');
RED.log.error(RED._('candy-egg-ws.errors.connect-error', { err: err }));
if (!that.closing) {
// try to reconnect every 3+ secs
that.tout = setTimeout(() => { that.startconn(); }, 3000 + Math.random() * 1000);
}
});
}
registerOutputNode(/*Node*/handler) {
this._outputNodes.push(handler);
}
removeOutputNode(/*Node*/handler) {
this._outputNodes.forEach((node, i, outputNodes) => {
if (node === handler) {
outputNodes.splice(i, 1);
}
});
if (this._inputNodes.length === 0 && this._outputNodes.length === 0) {
this.close();
}
}
registerInputNode(/*Node*/handler) {
this._inputNodes.push(handler);
}
removeInputNode(/*Node*/handler) {
this._inputNodes.forEach((node, i, inputNodes) => {
if (node === handler) {
inputNodes.splice(i, 1);
}
});
if (this._inputNodes.length === 0 && this._outputNodes.length === 0) {
this.close();
}
}
handleEvent(id,/*socket*/socket,/*String*/event,/*Object*/data,/*Object*/flags) {
let msg, wholemsg;
try {
wholemsg = JSON.parse(data);
}
catch(err) {
wholemsg = { payload:data };
}
msg = {
payload: data,
_session: {type:'candy-egg-ws',id:id}
};
wholemsg._session = msg._session;
for (let i = 0; i < this._inputNodes.length; i++) {
if (this._inputNodes[i].wholemsg) {
this._inputNodes[i].send(wholemsg);
} else {
this._inputNodes[i].send(msg);
}
}
RED.log.debug('flags:' + flags);
}
emit2all(event) {
for (let i = 0; i < this._inputNodes.length; i++) {
this._inputNodes[i].emit(event);
}
for (let i = 0; i < this._outputNodes.length; i++) {
this._outputNodes[i].emit(event);
}
}
close() {
this.closing = true;
this.server.close();
if (this.tout) { clearTimeout(this.tout); }
this.webSocketListeners.remove(this);
}
broadcast(data) {
let i;
try {
this.server.send(data);
}
catch(e) { // swallow any errors
RED.log.warn('ws:'+i+' : '+e);
}
}
reply(id,data) {
let session = this._clients[id];
if (session) {
try {
session.send(data);
}
catch(e) { // swallow any errors
}
}
}
}
class WebSocketListeners {
constructor() {
this.store = {};
}
get(node, options=null) {
if (!node.accountConfig) {
throw new Error(RED._('candy-egg-ws.errors.missing-conf'));
}
let key = node.account + ':' + node.path;
let listener = this.store[key];
if (!listener) {
listener = new WebSocketListener(node.accountConfig, node.account, node.path, this, options);
this.store[key] = listener;
}
return listener;
}
remove(listener) {
let key = listener.account + ':' + listener.path;
delete this.store[key];
}
reset(nodeId) {
let prefix = nodeId + ':';
let keys = [];
for (let key in this.store) {
if (this.store.hasOwnProperty(key) && key.indexOf(prefix) === 0) {
keys.push(key);
}
}
keys.forEach(key => {
delete this.store[key];
});
}
}
let webSocketListeners = new WebSocketListeners();
class CANDYEggAccountNode {
constructor(n) {
RED.nodes.createNode(this,n);
this.accountFqn = n.accountFqn;
this.loginUser = n.loginUser;
this.loginPassword = n.loginPassword;
this.secure = n.secure;
webSocketListeners.reset(n.id);
this.managed = n.managed;
// deploying implicit API clients (candy-ws)
let deviceManager = RED.settings.deviceManager;
if (this.managed && deviceManager && deviceManager.isWsClientInitialized) {
if (!deviceManager.isWsClientInitialized()) {
deviceManager.initWsClient(n.id, this, webSocketListeners);
}
}
}
}
RED.nodes.registerType('CANDY EGG account', CANDYEggAccountNode);
class WebSocketInNode {
constructor(n) {
RED.nodes.createNode(this, n);
let that = this;
that.account = n.account;
that.accountConfig = RED.nodes.getNode(that.account);
that.path = n.path;
that.wholemsg = n.wholemsg;
if (that.accountConfig) {
that.listenerConfig = webSocketListeners.get(that);
that.listenerConfig.registerInputNode(that);
that.on('opened', () => { that.status({fill:'green',shape:'dot',text:'candy-egg-ws.status.connected'}); });
that.on('erro', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.error'}); });
that.on('closed', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.disconnected'}); });
} else {
that.error(RED._('candy-egg-ws.errors.missing-conf'));
}
that.on('close', () => {
that.listenerConfig.removeInputNode(that);
});
}
}
RED.nodes.registerType('CANDY EGG websocket in', WebSocketInNode);
class WebSocketOutNode {
constructor(n) {
RED.nodes.createNode(this, n);
let that = this;
that.account = n.account;
that.accountConfig = RED.nodes.getNode(that.account);
that.path = n.path;
that.wholemsg = n.wholemsg;
if (that.accountConfig) {
that.listenerConfig = webSocketListeners.get(that);
that.listenerConfig.registerOutputNode(that);
that.on('opened', () => { that.status({fill:'green',shape:'dot',text:'candy-egg-ws.status.connected'}); });
that.on('erro', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.error'}); });
that.on('closed', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.disconnected'}); });
} else {
that.error(RED._('candy-egg-ws.errors.missing-conf'));
}
that.on('close', () => {
that.listenerConfig.removeOutputNode(that);
});
that.on('input', msg => {
let payload;
if (that.wholemsg) {
delete msg._session;
payload = JSON.stringify(msg);
} else if (msg.hasOwnProperty('payload')) {
if (!Buffer.isBuffer(msg.payload)) { // if it's not a buffer make sure it's a string.
payload = RED.util.ensureString(msg.payload);
}
else {
payload = msg.payload;
}
}
if (payload) {
if (msg._session && msg._session.type === 'candy-egg-ws') {
that.listenerConfig.reply(msg._session.id,payload);
} else {
that.listenerConfig.broadcast(payload);
}
}
});
}
}
RED.nodes.registerType('CANDY EGG websocket out',WebSocketOutNode);
}
| src/nodes/local-node-candy-egg/candy-egg-ws.es6.js | 'use strict';
import WebSocket from 'ws';
import urllib from 'url';
export default function(RED) {
class WebSocketListener {
constructor(accountConfig, account, path, webSocketListeners, options) {
this.accountConfig = accountConfig;
this.account = account;
this.path = path;
this.webSocketListeners = webSocketListeners;
this._inputNodes = []; // collection of thats that want to receive events
this._outputNodes = []; // node status event listeners
this._clients = {};
this.closing = false;
this.startconn(options); // start outbound connection
this.redirect = 0;
}
startconn(url) { // Connect to remote endpoint
let options = null;
if (url && typeof(url) === 'object') {
options = url;
url = null;
}
let conf = this.accountConfig;
let prefix = 'ws' + (conf.secure ? 's' : '') + '://';
prefix += conf.loginUser + ':' + conf.loginPassword + '@';
let accountId = conf.accountFqn.split('@');
prefix += accountId[1];
let path = this.path;
if (url) {
let urlobj = urllib.parse(url);
if (!urlobj.host) {
path = urlobj.href;
} else {
prefix = urlobj.href;
path = null;
}
} else {
prefix += '/' + accountId[0] + '/api';
}
if (path && path.length > 0 && path.charAt(0) !== '/') {
prefix += '/';
}
if (path) {
prefix += path;
}
let socket = new WebSocket(prefix, options);
this.server = socket; // keep for closing
this.handleConnection(socket);
}
handleConnection(/*socket*/socket) {
let that = this;
let id = (1+Math.random()*4294967295).toString(16);
socket.on('open', () => {
that.emit2all('opened');
that.redirect = 0;
});
socket.on('close', () => {
that.emit2all('closed');
if (!that.closing) {
// try to reconnect every 3+ secs
that.tout = setTimeout(() => { that.startconn(); }, 3000 + Math.random() * 1000);
}
});
socket.on('message', (data,flags) => {
that.handleEvent(id,socket,'message',data,flags);
});
socket.on('unexpected-response', (req, res) => {
that.emit2all('erro');
req.abort();
res.socket.end();
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
if (res.headers.location) {
if (this.redirect > 3) {
this.redirect = 0;
RED.log.error(RED._('candy-egg-ws.errors.too-many-redirects', { path: that.path, location: res.headers.location }));
} else {
++this.redirect;
return this.startconn(res.headers.location);
}
}
} else if (res.statusCode === 404) {
RED.log.error(RED._('candy-egg-ws.errors.wrong-path', { path: that.path }));
} else if (res.statusCode === 401) {
RED.log.error(RED._('candy-egg-ws.errors.auth-error', { path: that.path, user: this.accountConfig.loginUser }));
return; // never retry
} else {
RED.log.error(RED._('candy-egg-ws.errors.server-error', { path: that.path, status: res.statusCode }));
}
// try to reconnect every approx. 1 min
that.tout = setTimeout(() => { that.startconn(); }, 55000 + Math.random() * 10000);
this.redirect = 0;
});
socket.on('error', err => {
that.emit2all('erro');
RED.log.error(RED._('candy-egg-ws.errors.connect-error', { err: err }));
if (!that.closing) {
// try to reconnect every 3+ secs
that.tout = setTimeout(() => { that.startconn(); }, 3000 + Math.random() * 1000);
}
});
}
registerOutputNode(/*Node*/handler) {
this._outputNodes.push(handler);
}
removeOutputNode(/*Node*/handler) {
this._outputNodes.forEach((node, i, outputNodes) => {
if (node === handler) {
outputNodes.splice(i, 1);
}
});
if (this._inputNodes.length === 0 && this._outputNodes.length === 0) {
this.close();
}
}
registerInputNode(/*Node*/handler) {
this._inputNodes.push(handler);
}
removeInputNode(/*Node*/handler) {
this._inputNodes.forEach((node, i, inputNodes) => {
if (node === handler) {
inputNodes.splice(i, 1);
}
});
if (this._inputNodes.length === 0 && this._outputNodes.length === 0) {
this.close();
}
}
handleEvent(id,/*socket*/socket,/*String*/event,/*Object*/data,/*Object*/flags) {
let msg, wholemsg;
try {
wholemsg = JSON.parse(data);
}
catch(err) {
wholemsg = { payload:data };
}
msg = {
payload: data,
_session: {type:'candy-egg-ws',id:id}
};
wholemsg._session = msg._session;
for (let i = 0; i < this._inputNodes.length; i++) {
if (this._inputNodes[i].wholemsg) {
this._inputNodes[i].send(wholemsg);
} else {
this._inputNodes[i].send(msg);
}
}
RED.log.debug('flags:' + flags);
}
emit2all(event) {
for (let i = 0; i < this._inputNodes.length; i++) {
this._inputNodes[i].emit(event);
}
for (let i = 0; i < this._outputNodes.length; i++) {
this._outputNodes[i].emit(event);
}
}
close() {
this.closing = true;
this.server.close();
if (this.tout) { clearTimeout(this.tout); }
this.webSocketListeners.remove(this);
}
broadcast(data) {
let i;
try {
this.server.send(data);
}
catch(e) { // swallow any errors
RED.log.warn('ws:'+i+' : '+e);
}
}
reply(id,data) {
let session = this._clients[id];
if (session) {
try {
session.send(data);
}
catch(e) { // swallow any errors
}
}
}
}
class WebSocketListeners {
constructor() {
this.store = {};
}
get(node, options=null) {
if (!node.accountConfig) {
throw new Error(RED._('candy-egg-ws.errors.missing-conf'));
}
let key = node.account + ':' + node.path;
let listener = this.store[key];
if (!listener) {
listener = new WebSocketListener(node.accountConfig, node.account, node.path, this, options);
this.store[key] = listener;
}
return listener;
}
remove(listener) {
let key = listener.account + ':' + listener.path;
delete this.store[key];
}
reset(nodeId) {
let prefix = nodeId + ':';
let keys = [];
for (let key in this.store) {
if (this.store.hasOwnProperty(key) && key.indexOf(prefix) === 0) {
keys.push(key);
}
}
keys.forEach(key => {
delete this.store[key];
});
}
}
let webSocketListeners = new WebSocketListeners();
class CANDYEggAccountNode {
constructor(n) {
RED.nodes.createNode(this,n);
this.accountFqn = n.accountFqn;
this.loginUser = n.loginUser;
this.loginPassword = n.loginPassword;
this.secure = n.secure;
webSocketListeners.reset(n.id);
this.managed = n.managed;
// deploying implicit API clients (candy-ws)
let deviceManager = RED.settings.deviceManager;
if (this.managed && deviceManager && deviceManager.isWsClientInitialized) {
if (!deviceManager.isWsClientInitialized()) {
deviceManager.initWsClient(n.id, this, webSocketListeners);
}
}
}
}
RED.nodes.registerType('CANDY EGG account', CANDYEggAccountNode);
class WebSocketInNode {
constructor(n) {
RED.nodes.createNode(this, n);
let that = this;
that.account = n.account;
that.accountConfig = RED.nodes.getNode(that.account);
that.path = n.path;
that.wholemsg = n.wholemsg;
if (that.accountConfig) {
that.listenerConfig = webSocketListeners.get(that);
that.listenerConfig.registerInputNode(that);
that.on('opened', () => { that.status({fill:'green',shape:'dot',text:'candy-egg-ws.status.connected'}); });
that.on('erro', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.error'}); });
that.on('closed', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.disconnected'}); });
} else {
that.error(RED._('candy-egg-ws.errors.missing-conf'));
}
that.on('close', () => {
that.listenerConfig.removeInputNode(that);
});
}
}
RED.nodes.registerType('CANDY EGG websocket in', WebSocketInNode);
class WebSocketOutNode {
constructor(n) {
RED.nodes.createNode(this, n);
let that = this;
that.account = n.account;
that.accountConfig = RED.nodes.getNode(that.account);
that.path = n.path;
that.wholemsg = n.wholemsg;
if (that.accountConfig) {
that.listenerConfig = webSocketListeners.get(that);
that.listenerConfig.registerOutputNode(that);
that.on('opened', () => { that.status({fill:'green',shape:'dot',text:'candy-egg-ws.status.connected'}); });
that.on('erro', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.error'}); });
that.on('closed', () => { that.status({fill:'red',shape:'ring',text:'candy-egg-ws.status.disconnected'}); });
} else {
that.error(RED._('candy-egg-ws.errors.missing-conf'));
}
that.on('close', () => {
that.listenerConfig.removeOutputNode(that);
});
that.on('input', msg => {
let payload;
if (that.wholemsg) {
delete msg._session;
payload = JSON.stringify(msg);
} else if (msg.hasOwnProperty('payload')) {
if (!Buffer.isBuffer(msg.payload)) { // if it's not a buffer make sure it's a string.
payload = RED.util.ensureString(msg.payload);
}
else {
payload = msg.payload;
}
}
if (payload) {
if (msg._session && msg._session.type === 'candy-egg-ws') {
that.listenerConfig.reply(msg._session.id,payload);
} else {
that.listenerConfig.broadcast(payload);
}
}
});
}
}
RED.nodes.registerType('CANDY EGG websocket out',WebSocketOutNode);
}
| Allow users to pass WS upgrade request options
| src/nodes/local-node-candy-egg/candy-egg-ws.es6.js | Allow users to pass WS upgrade request options | <ide><path>rc/nodes/local-node-candy-egg/candy-egg-ws.es6.js
<ide> this._outputNodes = []; // node status event listeners
<ide> this._clients = {};
<ide> this.closing = false;
<del> this.startconn(options); // start outbound connection
<add> this.options = options || {};
<add> this.startconn(); // start outbound connection
<ide> this.redirect = 0;
<add> this.authRetry = 0;
<ide> }
<ide>
<ide> startconn(url) { // Connect to remote endpoint
<del> let options = null;
<del> if (url && typeof(url) === 'object') {
<del> options = url;
<del> url = null;
<del> }
<ide> let conf = this.accountConfig;
<ide> let prefix = 'ws' + (conf.secure ? 's' : '') + '://';
<ide> prefix += conf.loginUser + ':' + conf.loginPassword + '@';
<ide> if (path) {
<ide> prefix += path;
<ide> }
<del> let socket = new WebSocket(prefix, options);
<add> let socket = new WebSocket(prefix, this.options);
<ide> this.server = socket; // keep for closing
<ide> this.handleConnection(socket);
<ide> } |
|
Java | mit | 9c528586cedaa5a4a82d00f7f4b34e64413f8edf | 0 | codefacts/elasta,codefacts/Elastic-Components | package elasta.orm.json.sql;
import com.google.common.collect.ImmutableList;
import elasta.commons.SimpleCounter;
import elasta.core.promise.impl.Promises;
import elasta.core.promise.intfs.Promise;
import elasta.vertxutils.StaticUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Created by Jango on 9/25/2016.
*/
public class DbSqlImpl implements DbSql {
private final JDBCClient jdbcClient;
private final SqlBuilderUtils sqlBuilderUtils;
public DbSqlImpl(JDBCClient jdbcClient, SqlBuilderUtils sqlBuilderUtils) {
this.jdbcClient = jdbcClient;
this.sqlBuilderUtils = sqlBuilderUtils;
}
@Override
public Promise<ResultSet> query(String sql) {
return withConn(con -> Promises.exec(
defer -> con.query(sql, StaticUtils.deferred(defer))));
}
@Override
public Promise<ResultSet> query(String sql, JsonArray params) {
return withConn(con -> Promises.exec(
defer -> con.queryWithParams(sql, params, StaticUtils.deferred(defer))));
}
@Override
public <T> Promise<T> queryScalar(String sql) {
return query(sql).map(resultSet -> (T) resultSet.getResults().get(0).getValue(0));
}
@Override
public <T> Promise<T> queryScalar(String sql, JsonArray params) {
return query(sql, params).map(resultSet -> (T) resultSet.getResults().get(0).getValue(0));
}
@Override
public Promise<Void> update(String sql) {
return withConn(con -> Promises.exec(
defer -> con.update(sql, StaticUtils.deferred(defer))));
}
@Override
public Promise<Void> update(String sql, JsonArray params) {
return withConn(con -> Promises.exec(
defer -> con.updateWithParams(sql, params, StaticUtils.deferred(defer))));
}
@Override
public Promise<Void> update(List<String> sqlList) {
return execAndCommit(con -> Promises.exec(objectDefer -> {
con.batch(sqlList, StaticUtils.deferred(objectDefer));
}));
}
@Override
public Promise<Void> update(List<String> sqlList, List<JsonArray> paramsList) {
SimpleCounter counter = new SimpleCounter(0);
return execAndCommit(
con -> Promises.when(sqlList.stream()
.map(sql -> Promises.exec(dfr -> con.updateWithParams(sql, paramsList.get(counter.value++), StaticUtils.deferred(dfr))))
.collect(Collectors.toList())
).map(objects -> (Void) null));
}
@Override
public Promise<Void> insertJo(String table, JsonObject jsonObject) {
SqlAndParams sqlAndParams = sqlBuilderUtils.insertSql(table, jsonObject);
return update(sqlAndParams.getSql(), sqlAndParams.getParams());
}
@Override
public Promise<Void> insertJo(String table, List<JsonObject> sqlList) {
ImmutableList.Builder<String> sqlListBuilder = ImmutableList.builder();
ImmutableList.Builder<JsonArray> paramsListBuilder = ImmutableList.builder();
sqlList.stream().map(val -> sqlBuilderUtils.insertSql(table, val))
.forEach(insertSql -> {
sqlListBuilder.add(insertSql.getSql());
paramsListBuilder.add(insertSql.getParams());
});
return update(sqlListBuilder.build(), paramsListBuilder.build());
}
@Override
public Promise<Void> updateJo(String table, JsonObject jsonObject, String where, JsonArray params) {
SqlAndParams sqlAndParams = sqlBuilderUtils.updateSql(table, jsonObject, where, params);
return update(sqlAndParams.getSql(), sqlAndParams.getParams());
}
@Override
public Promise<Void> updateJo(List<UpdateTpl> sqlList) {
return execAndCommit(con -> Promises.when(
sqlList.stream().map(
updateTpl -> {
UpdateOperationType operationType = updateTpl.getUpdateOperationType();
SqlAndParams sqlAndParams;
if (operationType == UpdateOperationType.INSERT) {
sqlAndParams = sqlBuilderUtils.insertSql(updateTpl.getTable(), updateTpl.getData());
} else if (operationType == UpdateOperationType.UPDATE) {
sqlAndParams = sqlBuilderUtils.updateSql(updateTpl.getTable(), updateTpl.getData(), updateTpl.getWhere(), updateTpl.getJsonArray());
} else {
sqlAndParams = sqlBuilderUtils.deleteSql(updateTpl.getTable(), updateTpl.getWhere(), updateTpl.getJsonArray());
}
return Promises.exec(objectDefer -> {
con.updateWithParams(sqlAndParams.getSql(), sqlAndParams.getParams(), StaticUtils.deferred(objectDefer));
});
}).collect(Collectors.toList())
).map(objects -> (Void) null));
}
private Promise<SQLConnection> conn() {
return Promises.exec(defer -> {
jdbcClient.getConnection(StaticUtils.deferred(defer));
});
}
private <T> Promise<T> withConn(Function<SQLConnection, Promise<T>> function) {
return conn()
.mapP(
con -> {
try {
return function.apply(con)
.cmp(signal -> con.close());
} catch (Exception e) {
con.close();
return Promises.error(e);
}
}
);
}
private Promise<Void> execAndCommit(Function<SQLConnection, Promise<Void>> function) {
return conn()
.thenP(con -> Promises.exec(voidDefer -> con.setAutoCommit(false, StaticUtils.deferred(voidDefer))))
.mapP(
con -> {
try {
return function.apply(con)
.thenP(aVoid -> Promises.exec(voidDefer -> con.commit(StaticUtils.deferred(voidDefer))))
.errP(e -> Promises.exec(voidDefer -> con.rollback(StaticUtils.deferred(voidDefer))))
.cmp(signal -> con.close());
} catch (Exception e) {
con.close();
return Promises.error(e);
}
}
);
}
public static void main(String[] arg) {
System.out.println("ok");
}
}
| elasta-orm/src/main/java/elasta/orm/json/sql/DbSqlImpl.java | package elasta.orm.json.sql;
import com.google.common.collect.ImmutableList;
import elasta.commons.SimpleCounter;
import elasta.core.promise.impl.Promises;
import elasta.core.promise.intfs.Promise;
import elasta.vertxutils.StaticUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Created by Jango on 9/25/2016.
*/
public class DbSqlImpl implements DbSql {
private final JDBCClient jdbcClient;
private final SqlBuilderUtils sqlBuilderUtils;
public DbSqlImpl(JDBCClient jdbcClient, SqlBuilderUtils sqlBuilderUtils) {
this.jdbcClient = jdbcClient;
this.sqlBuilderUtils = sqlBuilderUtils;
}
@Override
public Promise<ResultSet> query(String sql) {
return withConn(con -> Promises.exec(
defer -> con.query(sql, StaticUtils.deferred(defer))));
}
@Override
public Promise<ResultSet> query(String sql, JsonArray params) {
return withConn(con -> Promises.exec(
defer -> con.queryWithParams(sql, params, StaticUtils.deferred(defer))));
}
@Override
public <T> Promise<T> queryScalar(String sql) {
return query(sql).map(resultSet -> (T) resultSet.getResults().get(0).getValue(0));
}
@Override
public <T> Promise<T> queryScalar(String sql, JsonArray params) {
return query(sql, params).map(resultSet -> (T) resultSet.getResults().get(0).getValue(0));
}
@Override
public Promise<Void> update(String sql) {
return withConn(con -> Promises.exec(
defer -> con.update(sql, StaticUtils.deferred(defer))));
}
@Override
public Promise<Void> update(String sql, JsonArray params) {
return withConn(con -> Promises.exec(
defer -> con.updateWithParams(sql, params, StaticUtils.deferred(defer))));
}
@Override
public Promise<Void> update(List<String> sqlList) {
return execAndCommit(con -> Promises.exec(objectDefer -> {
con.batch(sqlList, StaticUtils.deferred(objectDefer));
}));
}
@Override
public Promise<Void> update(List<String> sqlList, List<JsonArray> paramsList) {
SimpleCounter counter = new SimpleCounter(0);
return execAndCommit(
con -> Promises.when(sqlList.stream()
.map(sql -> Promises.exec(dfr -> con.updateWithParams(sql, paramsList.get(counter.value++), StaticUtils.deferred(dfr))))
.collect(Collectors.toList())
).map(objects -> (Void) null));
}
@Override
public Promise<Void> insertJo(String table, JsonObject jsonObject) {
SqlAndParams sqlAndParams = sqlBuilderUtils.insertSql(table, jsonObject);
return update(sqlAndParams.getSql(), sqlAndParams.getParams());
}
@Override
public Promise<Void> insertJo(String table, List<JsonObject> sqlList) {
ImmutableList.Builder<String> sqlListBuilder = ImmutableList.builder();
ImmutableList.Builder<JsonArray> paramsListBuilder = ImmutableList.builder();
sqlList.stream().map(val -> sqlBuilderUtils.insertSql(table, val))
.forEach(insertSql -> {
sqlListBuilder.add(insertSql.getSql());
paramsListBuilder.add(insertSql.getParams());
});
return update(sqlListBuilder.build(), paramsListBuilder.build());
}
@Override
public Promise<Void> updateJo(String table, JsonObject jsonObject, String where, JsonArray params) {
SqlAndParams sqlAndParams = sqlBuilderUtils.updateSql(table, jsonObject, where, params);
return update(sqlAndParams.getSql(), sqlAndParams.getParams());
}
@Override
public Promise<Void> updateJo(List<UpdateTpl> sqlList) {
return execAndCommit(con -> Promises.when(
sqlList.stream().map(
updateTpl -> {
UpdateOperationType operationType = updateTpl.getUpdateOperationType();
SqlAndParams sqlAndParams;
if (operationType == UpdateOperationType.INSERT) {
sqlAndParams = sqlBuilderUtils.insertSql(updateTpl.getTable(), updateTpl.getData());
} else if (operationType == UpdateOperationType.UPDATE) {
sqlAndParams = sqlBuilderUtils.updateSql(updateTpl.getTable(), updateTpl.getData(), updateTpl.getWhere(), updateTpl.getJsonArray());
} else {
sqlAndParams = sqlBuilderUtils.deleteSql(updateTpl.getTable(), updateTpl.getWhere(), updateTpl.getJsonArray());
}
return Promises.exec(objectDefer -> {
con.updateWithParams(sqlAndParams.getSql(), sqlAndParams.getParams(), StaticUtils.deferred(objectDefer));
});
}).collect(Collectors.toList())
).map(objects -> (Void) null));
}
private Promise<SQLConnection> conn() {
return Promises.exec(defer -> {
jdbcClient.getConnection(StaticUtils.deferred(defer));
});
}
private <T> Promise<T> withConn(Function<SQLConnection, Promise<T>> function) {
return conn()
.mapP(
con -> {
try {
return function.apply(con)
.errP(e -> Promises.exec(voidDefer -> con.rollback(StaticUtils.deferred(voidDefer))))
.cmp(signal -> con.close());
} catch (Exception e) {
con.close();
return Promises.error(e);
}
}
);
}
private Promise<Void> execAndCommit(Function<SQLConnection, Promise<Void>> function) {
return conn()
.thenP(con -> Promises.exec(voidDefer -> con.setAutoCommit(false, StaticUtils.deferred(voidDefer))))
.mapP(
con -> {
try {
return function.apply(con)
.thenP(aVoid -> Promises.exec(voidDefer -> con.commit(StaticUtils.deferred(voidDefer))))
.errP(e -> Promises.exec(voidDefer -> con.rollback(StaticUtils.deferred(voidDefer))))
.cmp(signal -> con.close());
} catch (Exception e) {
con.close();
return Promises.error(e);
}
}
);
}
public static void main(String[] arg) {
System.out.println("ok");
}
}
| fix error in DbSqlImpl.java
| elasta-orm/src/main/java/elasta/orm/json/sql/DbSqlImpl.java | fix error in DbSqlImpl.java | <ide><path>lasta-orm/src/main/java/elasta/orm/json/sql/DbSqlImpl.java
<ide> con -> {
<ide> try {
<ide> return function.apply(con)
<del> .errP(e -> Promises.exec(voidDefer -> con.rollback(StaticUtils.deferred(voidDefer))))
<ide> .cmp(signal -> con.close());
<ide> } catch (Exception e) {
<ide> con.close(); |
|
JavaScript | apache-2.0 | 202d5e6a5f16ed1ad8e7cb7cc4d999d8a5260324 | 0 | chughts/node-red-node-watson,arlemi/node-red-node-watson,chughts/node-red-node-watson,arlemi/node-red-node-watson | /**
* Copyright 2013,2015, 2016 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
const SERVICE_IDENTIFIER = 'visual-recognition';
const VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
var serviceutils = require('../../utilities/service-utils'),
//watson = require('watson-developer-cloud'),
imageType = require('image-type'),
url = require('url'),
temp = require('temp'),
fileType = require('file-type'),
fs = require('fs'),
async = require('async'),
sAPIKey = null,
service = null;
// temp is being used for file streaming to allow the file to arrive so it can be processed.
temp.track();
service = serviceutils.getServiceCreds(SERVICE_IDENTIFIER);
if (service) {
sAPIKey = service.api_key;
}
RED.httpAdmin.get('/watson-visual-recognition/vcap', function(req, res) {
res.json(service ? {
bound_service: true
} : null);
});
function imageCheck(data) {
return data instanceof Buffer && imageType(data) !== null;
}
function urlCheck(str) {
var parsed = url.parse(str);
return (!!parsed.hostname && !!parsed.protocol && str.indexOf(' ') < 0);
}
function stream_buffer(file, contents, cb) {
fs.writeFile(file, contents, function(err) {
if (err) {
throw err;
}
cb();
});
}
function verifyPayload(msg) {
if (!msg.payload) {
return Promise.reject('Missing property: msg.payload');
} else {
return Promise.resolve();
}
}
function verifyInputs(feature, msg) {
switch (feature) {
case 'classifyImage':
case 'detectFaces':
case 'recognizeText':
if (typeof msg.payload === 'boolean' || typeof msg.payload === 'number') {
return Promise.reject('Bad format : msg.payload must be a URL string or a Node.js Buffer');
}
break;
default:
return Promise.resolve();
break;
}
}
function verifyServiceCredentials(node, msg) {
// If it is present the newly provided user entered key
// takes precedence over the existing one.
node.apikey = sAPIKey || node.credentials.apikey;
if (!node.apikey) {
return Promise.reject('Missing Watson Visual Recognition API service credentials');
}
node.service = new VisualRecognitionV3({
api_key: node.apikey,
version_date: VisualRecognitionV3.VERSION_DATE_2016_05_20
});
return Promise.resolve();
}
function processTheResponse(body, feature, node, msg) {
if (body == null) {
return Promise.reject('call to watson visual recognition v3 service failed');
} else if (body.images != null & body.images[0].error) {
return Promise.reject(body.images[0].error);
} else {
if (feature === 'deleteClassifier') {
msg.result = 'Successfully deleted classifier_id: ' + msg.params.classifier_id;
} else {
msg.result = body;
}
return Promise.resolve();
}
}
function processResponse(err, body, feature, node, msg) {
if (err != null && body == null) {
node.status({
fill: 'red',
shape: 'ring',
text: 'call to watson visual recognition v3 service failed'
});
msg.result = {};
if (err.code == null) {
msg.result['error'] = err;
} else {
msg.result['error_code'] = err.code;
if (!err.error) {
msg.result['error'] = err.error;
}
}
node.error(err);
return;
} else if (err == null && body != null && body.images != null &&
body.images[0].error) {
node.status({
fill: 'red',
shape: 'ring',
text: 'call to watson visual recognition v3 service failed'
});
msg.result = {};
msg.result['error_id'] = body.images[0].error.error_id;
msg.result['error'] = body.images[0].error.description;
node.send(msg);
} else {
if (feature === 'deleteClassifier') {
msg.result = 'Successfully deleted classifier_id: ' + msg.params.classifier_id;
} else {
msg.result = body;
}
node.send(msg);
node.status({});
}
}
function prepareParamsCommon(params, node, msg, cb) {
if (imageCheck(msg.payload)) {
temp.open({
suffix: '.' + fileType(msg.payload).ext
}, function(err, info) {
if (err) {
this.status({
fill: 'red',
shape: 'ring',
text: 'unable to open image stream'
});
node.error('Node has been unable to open the image stream', msg);
return cb();
}
stream_buffer(info.path, msg.payload, function() {
params['images_file'] = fs.createReadStream(info.path);
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
cb();
});
});
} else if (urlCheck(msg.payload)) {
params['url'] = msg.payload;
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
return cb();
} else {
node.status({
fill: 'red',
shape: 'ring',
text: 'payload is invalid'
});
node.error('Payload must be either an image buffer or a string representing a url', msg);
}
}
function prepareCommonParams(params, node, msg) {
var p = new Promise(function resolver(resolve, reject){
if (imageCheck(msg.payload)) {
var ft = fileType(msg.payload);
var ext = ft ? ft.ext : 'tmp';
temp.open({
suffix: '.' + ext
}, function(err, info) {
if (err) {
reject('Node has been unable to open the image stream');
}
stream_buffer(info.path, msg.payload, function() {
params['images_file'] = fs.createReadStream(info.path);
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
resolve();
});
});
} else if (urlCheck(msg.payload)) {
params['url'] = msg.payload;
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
resolve();
} else {
reject('Payload must be either an image buffer or a string representing a url');
}
});
return p;
}
function addTask(asyncTasks, msg, k, listParams, node) {
asyncTasks.push(function(callback) {
var buffer = msg.params[k];
temp.open({
suffix: '.' + fileType(buffer).ext
}, function(err, info) {
if (err) {
node.status({
fill: 'red',
shape: 'ring',
text: 'unable to open image stream'
});
node.error('Node has been unable to open the image stream', msg);
return callback('open error on ' + k);
}
stream_buffer(info.path, msg.params[k], function() {
listParams[k] = fs.createReadStream(info.path);
callback(null, k);
});
});
});
}
function prepareParamsCreateClassifier(params, node, msg, cb) {
var listParams = {},
asyncTasks = [],
k = null;
for (k in msg.params) {
if (k.indexOf('_examples') >= 0) {
addTask(asyncTasks, msg, k, listParams, node);
} else if (k === 'name') {
listParams[k] = msg.params[k];
}
}
async.parallel(asyncTasks, function(error) {
if (error) {
throw error;
}
for (var p in listParams) {
if (p != null) {
params[p] = listParams[p];
}
}
cb();
});
}
function performDeleteAllClassifiers(params, node, msg) {
node.service.listClassifiers(params, function(err, body) {
node.status({});
if (err) {
node.status({
fill: 'red',
shape: 'ring',
text: 'Delete All : call to listClassifiers failed'
});
node.error(err, msg);
} else {
// Array to hold async tasks
var asyncTasks = [],
nbTodelete = 0,
nbdeleted = 0;
nbTodelete = body.classifiers.length;
body.classifiers.forEach(function(aClassifier) {
asyncTasks.push(function(cb) {
var parms = {};
parms.classifier_id = aClassifier.classifier_id;
node.service.deleteClassifier(parms, function(err) {
if (err) {
node.error(err, msg);
return cb('error');
}
nbdeleted++;
cb(null, parms.classifier_id);
});
});
});
async.parallel(asyncTasks, function(error, deletedList) {
if (deletedList.length === nbTodelete) {
msg.result = 'All custom classifiers have been deleted.';
} else {
msg.result = 'Some Classifiers could have not been deleted;' +
'See log for errors.';
}
node.send(msg);
node.status({});
});
}
});
}
function old_executeService(feature, params, node, msg) {
switch (feature) {
case 'classifyImage':
prepareParamsCommon(params, node, msg, function() {
node.service.classify(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'detectFaces':
prepareParamsCommon(params, node, msg, function() {
node.service.detectFaces(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'recognizeText':
prepareParamsCommon(params, node, msg, function() {
node.service.recognizeText(params, function(err, body) {
if (err) {} else {
if (body.images) {}
}
processResponse(err, body, feature, node, msg);
});
});
break;
}
}
function invokeService(feature, params, node, msg) {
var p = new Promise(function resolver(resolve, reject){
switch (feature) {
case 'classifyImage':
node.service.classify(params, function(err, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
break;
case 'detectFaces':
node.service.detectFaces(params, function(err, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
break;
case 'recognizeText':
node.service.recognizeText(params, function(err, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
break;
}
});
return p;
}
function executeService(feature, params, node, msg) {
var p = prepareCommonParams(params, node, msg)
.then(function(){
return invokeService(feature, params, node, msg);
})
.then(function(body){
return processTheResponse(body, feature, node, msg);
});
return p;
}
function executeUtilService(feature, params, node, msg) {
switch (feature) {
case 'createClassifier':
prepareParamsCreateClassifier(params, node, msg, function() {
node.service.createClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'retrieveClassifiersList':
node.service.listClassifiers(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'retrieveClassifierDetails':
params['classifier_id'] = msg.params['classifier_id'];
node.service.getClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'deleteClassifier':
params['classifier_id'] = msg.params['classifier_id'];
node.service.deleteClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'deleteAllClassifiers':
performDeleteAllClassifiers(params, node, msg);
break;
}
}
function old_execute(feature, params, node, msg) {
node.status({
fill: 'blue',
shape: 'dot',
text: 'Calling ' + feature + ' ...'
});
if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
old_executeService(feature, params, node, msg);
} else {
executeUtilService(feature, params, node, msg);
}
}
function execute(feature, params, node, msg) {
node.status({
fill: 'blue',
shape: 'dot',
text: 'Calling ' + feature + ' ...'
});
if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
return executeService(feature, params, node, msg);
//return Promise.resolve();
} else {
executeUtilService(feature, params, node, msg);
return Promise.resolve();
}
}
// This is the Watson Visual Recognition V3 Node
function WatsonVisualRecognitionV3Node(config) {
var node = this,
b = false,
feature = config['image-feature'];
RED.nodes.createNode(this, config);
node.config = config;
node.on('input', function(msg) {
var params = {};
node.status({});
// so there is at most 1 temp file at a time (did not found a better solution...)
//temp.cleanup();
verifyPayload(msg)
.then(function(){
return verifyInputs(feature, msg);
})
.then(function(){
return verifyServiceCredentials(node, msg);
})
.then(function(){
return execute(feature, params, node, msg);
})
.then(function(){
temp.cleanup();
node.status({});
node.send(msg);
})
.catch(function(err) {
var messageTxt = err.error ? err.error : err;
node.status({
fill: 'red',
shape: 'dot',
text: messageTxt
});
node.error(messageTxt, msg);
});
});
}
RED.nodes.registerType('visual-recognition-v3', WatsonVisualRecognitionV3Node, {
credentials: {
apikey: {
type: 'password'
}
}
});
RED.nodes.registerType('visual-recognition-util-v3', WatsonVisualRecognitionV3Node, {
credentials: {
apikey: {
type: 'password'
}
}
});
};
| services/visual_recognition/v3.js | /**
* Copyright 2013,2015, 2016 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
const SERVICE_IDENTIFIER = 'visual-recognition';
const VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
var serviceutils = require('../../utilities/service-utils'),
//watson = require('watson-developer-cloud'),
imageType = require('image-type'),
url = require('url'),
temp = require('temp'),
fileType = require('file-type'),
fs = require('fs'),
async = require('async'),
sAPIKey = null,
service = null;
// temp is being used for file streaming to allow the file to arrive so it can be processed.
temp.track();
service = serviceutils.getServiceCreds(SERVICE_IDENTIFIER);
if (service) {
sAPIKey = service.api_key;
}
RED.httpAdmin.get('/watson-visual-recognition/vcap', function(req, res) {
res.json(service ? {
bound_service: true
} : null);
});
function imageCheck(data) {
return data instanceof Buffer && imageType(data) !== null;
}
function urlCheck(str) {
var parsed = url.parse(str);
return (!!parsed.hostname && !!parsed.protocol && str.indexOf(' ') < 0);
}
function stream_buffer(file, contents, cb) {
fs.writeFile(file, contents, function(err) {
if (err) {
throw err;
}
cb();
});
}
function verifyPayload(msg) {
if (!msg.payload) {
return Promise.reject('Missing property: msg.payload');
} else {
return Promise.resolve();
}
}
function verifyInputs(feature, msg) {
switch (feature) {
case 'classifyImage':
case 'detectFaces':
case 'recognizeText':
if (typeof msg.payload === 'boolean' || typeof msg.payload === 'number') {
return Promise.reject('Bad format : msg.payload must be a URL string or a Node.js Buffer');
}
break;
default:
return Promise.resolve();
break;
}
}
function verifyServiceCredentials(node, msg) {
// If it is present the newly provided user entered key
// takes precedence over the existing one.
node.apikey = sAPIKey || node.credentials.apikey;
if (!node.apikey) {
return Promise.reject('Missing Watson Visual Recognition API service credentials');
}
node.service = new VisualRecognitionV3({
api_key: node.apikey,
version_date: VisualRecognitionV3.VERSION_DATE_2016_05_20
});
return Promise.resolve();
}
function processResponse(err, body, feature, node, msg) {
if (err != null && body == null) {
node.status({
fill: 'red',
shape: 'ring',
text: 'call to watson visual recognition v3 service failed'
});
msg.result = {};
if (err.code == null) {
msg.result['error'] = err;
} else {
msg.result['error_code'] = err.code;
if (!err.error) {
msg.result['error'] = err.error;
}
}
node.error(err);
return;
} else if (err == null && body != null && body.images != null &&
body.images[0].error) {
node.status({
fill: 'red',
shape: 'ring',
text: 'call to watson visual recognition v3 service failed'
});
msg.result = {};
msg.result['error_id'] = body.images[0].error.error_id;
msg.result['error'] = body.images[0].error.description;
node.send(msg);
} else {
if (feature === 'deleteClassifier') {
msg.result = 'Successfully deleted classifier_id: ' + msg.params.classifier_id;
} else {
msg.result = body;
}
node.send(msg);
node.status({});
}
}
function prepareParamsCommon(params, node, msg, cb) {
if (imageCheck(msg.payload)) {
temp.open({
suffix: '.' + fileType(msg.payload).ext
}, function(err, info) {
if (err) {
this.status({
fill: 'red',
shape: 'ring',
text: 'unable to open image stream'
});
node.error('Node has been unable to open the image stream', msg);
return cb();
}
stream_buffer(info.path, msg.payload, function() {
params['images_file'] = fs.createReadStream(info.path);
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
cb();
});
});
} else if (urlCheck(msg.payload)) {
params['url'] = msg.payload;
if (msg.params != null && msg.params.classifier_ids != null) {
params['classifier_ids'] = msg.params['classifier_ids'];
}
if (msg.params != null && msg.params.owners != null) {
params['owners'] = msg.params['owners'];
}
if (msg.params != null && msg.params.threshold != null) {
params['threshold'] = msg.params['threshold'];
}
if (node.config != null && node.config.lang != null) {
params['Accept-Language'] = node.config.lang;
}
if (msg.params != null && msg.params.accept_language != null) {
params['Accept-Language'] = msg.params['accept_language'];
}
return cb();
} else {
node.status({
fill: 'red',
shape: 'ring',
text: 'payload is invalid'
});
node.error('Payload must be either an image buffer or a string representing a url', msg);
}
}
function addTask(asyncTasks, msg, k, listParams, node) {
asyncTasks.push(function(callback) {
var buffer = msg.params[k];
temp.open({
suffix: '.' + fileType(buffer).ext
}, function(err, info) {
if (err) {
node.status({
fill: 'red',
shape: 'ring',
text: 'unable to open image stream'
});
node.error('Node has been unable to open the image stream', msg);
return callback('open error on ' + k);
}
stream_buffer(info.path, msg.params[k], function() {
listParams[k] = fs.createReadStream(info.path);
callback(null, k);
});
});
});
}
function prepareParamsCreateClassifier(params, node, msg, cb) {
var listParams = {},
asyncTasks = [],
k = null;
for (k in msg.params) {
if (k.indexOf('_examples') >= 0) {
addTask(asyncTasks, msg, k, listParams, node);
} else if (k === 'name') {
listParams[k] = msg.params[k];
}
}
async.parallel(asyncTasks, function(error) {
if (error) {
throw error;
}
for (var p in listParams) {
if (p != null) {
params[p] = listParams[p];
}
}
cb();
});
}
function performDeleteAllClassifiers(params, node, msg) {
node.service.listClassifiers(params, function(err, body) {
node.status({});
if (err) {
node.status({
fill: 'red',
shape: 'ring',
text: 'Delete All : call to listClassifiers failed'
});
node.error(err, msg);
} else {
// Array to hold async tasks
var asyncTasks = [],
nbTodelete = 0,
nbdeleted = 0;
nbTodelete = body.classifiers.length;
body.classifiers.forEach(function(aClassifier) {
asyncTasks.push(function(cb) {
var parms = {};
parms.classifier_id = aClassifier.classifier_id;
node.service.deleteClassifier(parms, function(err) {
if (err) {
node.error(err, msg);
return cb('error');
}
nbdeleted++;
cb(null, parms.classifier_id);
});
});
});
async.parallel(asyncTasks, function(error, deletedList) {
if (deletedList.length === nbTodelete) {
msg.result = 'All custom classifiers have been deleted.';
} else {
msg.result = 'Some Classifiers could have not been deleted;' +
'See log for errors.';
}
node.send(msg);
node.status({});
});
}
});
}
function old_executeService(feature, params, node, msg) {
switch (feature) {
case 'classifyImage':
prepareParamsCommon(params, node, msg, function() {
node.service.classify(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'detectFaces':
prepareParamsCommon(params, node, msg, function() {
node.service.detectFaces(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'recognizeText':
prepareParamsCommon(params, node, msg, function() {
node.service.recognizeText(params, function(err, body) {
if (err) {} else {
if (body.images) {}
}
processResponse(err, body, feature, node, msg);
});
});
break;
}
}
function executeService(feature, params, node, msg) {
switch (feature) {
case 'classifyImage':
prepareParamsCommon(params, node, msg, function() {
node.service.classify(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'detectFaces':
prepareParamsCommon(params, node, msg, function() {
node.service.detectFaces(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'recognizeText':
prepareParamsCommon(params, node, msg, function() {
node.service.recognizeText(params, function(err, body) {
if (err) {} else {
if (body.images) {}
}
processResponse(err, body, feature, node, msg);
});
});
break;
}
}
function executeUtilService(feature, params, node, msg) {
switch (feature) {
case 'createClassifier':
prepareParamsCreateClassifier(params, node, msg, function() {
node.service.createClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
});
break;
case 'retrieveClassifiersList':
node.service.listClassifiers(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'retrieveClassifierDetails':
params['classifier_id'] = msg.params['classifier_id'];
node.service.getClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'deleteClassifier':
params['classifier_id'] = msg.params['classifier_id'];
node.service.deleteClassifier(params, function(err, body) {
processResponse(err, body, feature, node, msg);
});
break;
case 'deleteAllClassifiers':
performDeleteAllClassifiers(params, node, msg);
break;
}
}
function old_execute(feature, params, node, msg) {
node.status({
fill: 'blue',
shape: 'dot',
text: 'Calling ' + feature + ' ...'
});
if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
executeService(feature, params, node, msg);
} else {
executeUtilService(feature, params, node, msg);
}
}
function execute(feature, params, node, msg) {
node.status({
fill: 'blue',
shape: 'dot',
text: 'Calling ' + feature + ' ...'
});
if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
executeService(feature, params, node, msg);
return Promise.resolve();
} else {
executeUtilService(feature, params, node, msg);
return Promise.resolve();
}
}
// This is the Watson Visual Recognition V3 Node
function WatsonVisualRecognitionV3Node(config) {
var node = this,
b = false,
feature = config['image-feature'];
RED.nodes.createNode(this, config);
node.config = config;
node.on('input', function(msg) {
var params = {};
node.status({});
// so there is at most 1 temp file at a time (did not found a better solution...)
//temp.cleanup();
verifyPayload(msg)
.then(function(){
return verifyInputs(feature, msg);
})
.then(function(){
return verifyServiceCredentials(node, msg);
})
.then(function(){
return execute(feature, params, node, msg);
})
.then(function(){
temp.cleanup();
})
.catch(function(err) {
var messageTxt = err.error ? err.error : err;
node.status({
fill: 'red',
shape: 'dot',
text: messageTxt
});
node.error(messageTxt, msg);
});
});
}
RED.nodes.registerType('visual-recognition-v3', WatsonVisualRecognitionV3Node, {
credentials: {
apikey: {
type: 'password'
}
}
});
RED.nodes.registerType('visual-recognition-util-v3', WatsonVisualRecognitionV3Node, {
credentials: {
apikey: {
type: 'password'
}
}
});
};
| Add promises to VR
| services/visual_recognition/v3.js | Add promises to VR | <ide><path>ervices/visual_recognition/v3.js
<ide> return Promise.resolve();
<ide> }
<ide>
<add>
<add> function processTheResponse(body, feature, node, msg) {
<add> if (body == null) {
<add> return Promise.reject('call to watson visual recognition v3 service failed');
<add> } else if (body.images != null & body.images[0].error) {
<add> return Promise.reject(body.images[0].error);
<add> } else {
<add> if (feature === 'deleteClassifier') {
<add> msg.result = 'Successfully deleted classifier_id: ' + msg.params.classifier_id;
<add> } else {
<add> msg.result = body;
<add> }
<add> return Promise.resolve();
<add> }
<add> }
<ide>
<ide> function processResponse(err, body, feature, node, msg) {
<ide> if (err != null && body == null) {
<ide> }
<ide> }
<ide>
<add>
<add>
<ide> function prepareParamsCommon(params, node, msg, cb) {
<ide> if (imageCheck(msg.payload)) {
<ide> temp.open({
<ide> });
<ide> node.error('Payload must be either an image buffer or a string representing a url', msg);
<ide> }
<add> }
<add>
<add> function prepareCommonParams(params, node, msg) {
<add> var p = new Promise(function resolver(resolve, reject){
<add> if (imageCheck(msg.payload)) {
<add> var ft = fileType(msg.payload);
<add> var ext = ft ? ft.ext : 'tmp';
<add> temp.open({
<add> suffix: '.' + ext
<add> }, function(err, info) {
<add> if (err) {
<add> reject('Node has been unable to open the image stream');
<add> }
<add> stream_buffer(info.path, msg.payload, function() {
<add> params['images_file'] = fs.createReadStream(info.path);
<add> if (msg.params != null && msg.params.classifier_ids != null) {
<add> params['classifier_ids'] = msg.params['classifier_ids'];
<add> }
<add> if (msg.params != null && msg.params.owners != null) {
<add> params['owners'] = msg.params['owners'];
<add> }
<add> if (msg.params != null && msg.params.threshold != null) {
<add> params['threshold'] = msg.params['threshold'];
<add> }
<add> if (node.config != null && node.config.lang != null) {
<add> params['Accept-Language'] = node.config.lang;
<add> }
<add> if (msg.params != null && msg.params.accept_language != null) {
<add> params['Accept-Language'] = msg.params['accept_language'];
<add> }
<add> resolve();
<add> });
<add> });
<add> } else if (urlCheck(msg.payload)) {
<add> params['url'] = msg.payload;
<add> if (msg.params != null && msg.params.classifier_ids != null) {
<add> params['classifier_ids'] = msg.params['classifier_ids'];
<add> }
<add> if (msg.params != null && msg.params.owners != null) {
<add> params['owners'] = msg.params['owners'];
<add> }
<add> if (msg.params != null && msg.params.threshold != null) {
<add> params['threshold'] = msg.params['threshold'];
<add> }
<add> if (node.config != null && node.config.lang != null) {
<add> params['Accept-Language'] = node.config.lang;
<add> }
<add> if (msg.params != null && msg.params.accept_language != null) {
<add> params['Accept-Language'] = msg.params['accept_language'];
<add> }
<add> resolve();
<add> } else {
<add> reject('Payload must be either an image buffer or a string representing a url');
<add> }
<add> });
<add> return p;
<ide> }
<ide>
<ide>
<ide> }
<ide> }
<ide>
<add> function invokeService(feature, params, node, msg) {
<add> var p = new Promise(function resolver(resolve, reject){
<add> switch (feature) {
<add> case 'classifyImage':
<add> node.service.classify(params, function(err, body) {
<add> if (err) {
<add> reject(err);
<add> } else {
<add> resolve(body);
<add> }
<add> });
<add> break;
<add> case 'detectFaces':
<add> node.service.detectFaces(params, function(err, body) {
<add> if (err) {
<add> reject(err);
<add> } else {
<add> resolve(body);
<add> }
<add> });
<add> break;
<add> case 'recognizeText':
<add> node.service.recognizeText(params, function(err, body) {
<add> if (err) {
<add> reject(err);
<add> } else {
<add> resolve(body);
<add> }
<add> });
<add> break;
<add> }
<add> });
<add> return p;
<add> }
<add>
<ide> function executeService(feature, params, node, msg) {
<del> switch (feature) {
<del> case 'classifyImage':
<del> prepareParamsCommon(params, node, msg, function() {
<del> node.service.classify(params, function(err, body) {
<del> processResponse(err, body, feature, node, msg);
<del> });
<del> });
<del> break;
<del> case 'detectFaces':
<del> prepareParamsCommon(params, node, msg, function() {
<del> node.service.detectFaces(params, function(err, body) {
<del> processResponse(err, body, feature, node, msg);
<del> });
<del> });
<del> break;
<del> case 'recognizeText':
<del> prepareParamsCommon(params, node, msg, function() {
<del> node.service.recognizeText(params, function(err, body) {
<del> if (err) {} else {
<del> if (body.images) {}
<del> }
<del> processResponse(err, body, feature, node, msg);
<del> });
<del> });
<del> break;
<del> }
<add> var p = prepareCommonParams(params, node, msg)
<add> .then(function(){
<add> return invokeService(feature, params, node, msg);
<add> })
<add> .then(function(body){
<add> return processTheResponse(body, feature, node, msg);
<add> });
<add> return p;
<ide> }
<ide>
<ide>
<ide> text: 'Calling ' + feature + ' ...'
<ide> });
<ide> if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
<del> executeService(feature, params, node, msg);
<add> old_executeService(feature, params, node, msg);
<ide> } else {
<ide> executeUtilService(feature, params, node, msg);
<ide> }
<ide> text: 'Calling ' + feature + ' ...'
<ide> });
<ide> if (feature === 'classifyImage' || feature === 'detectFaces' || feature === 'recognizeText') {
<del> executeService(feature, params, node, msg);
<del> return Promise.resolve();
<add> return executeService(feature, params, node, msg);
<add> //return Promise.resolve();
<ide> } else {
<ide> executeUtilService(feature, params, node, msg);
<ide> return Promise.resolve();
<ide> })
<ide> .then(function(){
<ide> temp.cleanup();
<add> node.status({});
<add> node.send(msg);
<ide> })
<ide> .catch(function(err) {
<ide> var messageTxt = err.error ? err.error : err; |
|
Java | epl-1.0 | 31a42289f3c84636205126c506663a56efca2482 | 0 | zsmartsystems/com.zsmartsystems.zigbee,cschwer/com.zsmartsystems.zigbee | /**
* Copyright (c) 2016-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.dongle.telegesis.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisCommand;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisEvent;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisFrame;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisStatusCode;
import com.zsmartsystems.zigbee.transport.ZigBeePort;
/**
* Frame parser for the Telegesis AT command protocol.
*
* @author Chris Jackson
*
*/
public class TelegesisFrameHandler {
/**
* The logger.
*/
private final Logger logger = LoggerFactory.getLogger(TelegesisFrameHandler.class);
/**
* The queue of {@link TelegesisFrame} frames waiting to be sent
*/
private final Queue<TelegesisCommand> sendQueue = new LinkedList<TelegesisCommand>();
private ExecutorService executor = Executors.newCachedThreadPool();
/**
* List of listeners waiting for commands to complete
*/
private final List<TelegesisListener> transactionListeners = new ArrayList<TelegesisListener>();
/**
* List of event listeners
*/
private final List<TelegesisEventListener> eventListeners = new ArrayList<TelegesisEventListener>();
/**
* The port.
*/
private ZigBeePort serialPort;
/**
* The parser parserThread.
*/
private Thread parserThread = null;
/**
* Object to synchronise access to sentCommand
*/
private Object commandLock = new Object();
/**
* The command that we're currently sending, or null if no command is being transacted
*/
private TelegesisCommand sentCommand = null;
/**
* Flag reflecting that parser has been closed and parser parserThread should exit.
*/
private boolean closeHandler = false;
/**
* Scheduler used as a timer to abort any transactions that don't complete in a timely manner
*/
private ScheduledExecutorService timeoutScheduler;
/**
* The future be used for timeouts
*/
private ScheduledFuture<?> timeoutTimer = null;
/**
* The maximum number of milliseconds to wait for the response from the stick once the request was sent
*/
private final int DEFAULT_TRANSACTION_TIMEOUT = 500;
/**
* The maximum number of milliseconds to wait for the completion of the transaction after it's queued
*/
private final int DEFAULT_COMMAND_TIMEOUT = 10000;
private int transactionTimeout = DEFAULT_TRANSACTION_TIMEOUT;
private int commandTimeout = DEFAULT_COMMAND_TIMEOUT;
enum RxStateMachine {
WAITING,
RECEIVE_CMD,
RECEIVE_ASCII,
RECEIVE_BINARY
}
/**
* Construct which sets input stream where the packet is read from the and
* handler which further processes the received packet.
*
* @param serialPort the {@link ZigBeePort}
*/
public void start(final ZigBeePort serialPort) {
this.serialPort = serialPort;
this.timeoutScheduler = Executors.newSingleThreadScheduledExecutor();
parserThread = new Thread("TelegesisFrameHandler") {
@Override
public void run() {
logger.debug("TelegesisFrameHandler thread started");
while (!closeHandler) {
try {
// Get a packet from the serial port
int[] responseData = getPacket();
if (responseData == null) {
continue;
}
StringBuilder builder = new StringBuilder();
for (int value : responseData) {
builder.append(String.format(" %02X", value));
}
logger.debug("TELEGESIS RX: Data{}", builder.toString());
// Use the Event Factory to get an event
TelegesisEvent event = TelegesisEventFactory.getTelegesisFrame(responseData);
if (event != null) {
notifyEventReceived(event);
continue;
}
// If we're sending a command, then we need to process any responses
synchronized (commandLock) {
if (sentCommand != null) {
boolean done;
try {
done = sentCommand.deserialize(responseData);
} catch (Exception e) {
logger.debug("Exception deserialising frame {}. Transaction will complete. ",
builder.toString(), e);
done = true;
}
if (done) {
// Command completed
notifyTransactionComplete(sentCommand);
sentCommand = null;
sendNextFrame();
}
}
}
} catch (Exception e) {
logger.error("TelegesisFrameHandler exception", e);
}
}
logger.debug("TelegesisFrameHandler thread exited.");
}
};
parserThread.setDaemon(true);
parserThread.start();
}
private int[] getPacket() {
int[] inputBuffer = new int[120];
int inputBufferLength = 0;
RxStateMachine rxState = RxStateMachine.WAITING;
int binaryLength = 0;
logger.trace("TELEGESIS: Get Packet");
while (!closeHandler) {
int val = serialPort.read();
if (val == -1) {
// Timeout
continue;
}
if (inputBufferLength >= inputBuffer.length) {
// If we overrun the buffer, reset and go to WAITING mode
inputBufferLength = 0;
rxState = RxStateMachine.WAITING;
logger.debug("TELEGESIS RX buffer overrun - resetting!");
}
logger.trace("TELEGESIS RX: {}", String.format("%02X %c", val, val));
switch (rxState) {
case WAITING:
// Ignore any CR and LF
if (val == '\n' || val == '\r') {
continue;
}
inputBuffer[inputBufferLength++] = val;
rxState = RxStateMachine.RECEIVE_CMD;
break;
case RECEIVE_CMD:
if (val == '\n' || val == '\r') {
// We're done
// Return the packet without the CRLF on the end
return Arrays.copyOfRange(inputBuffer, 0, inputBufferLength);
}
// Here we wait for the colon
// This allows us to avoid switching into binary mode for ATS responses
inputBuffer[inputBufferLength++] = val;
if (val == ':') {
rxState = RxStateMachine.RECEIVE_ASCII;
}
break;
case RECEIVE_ASCII:
if (val == '\n' || val == '\r') {
// We're done
// Return the packet without the CRLF on the end
return Arrays.copyOfRange(inputBuffer, 0, inputBufferLength);
}
inputBuffer[inputBufferLength++] = val;
// Handle switching to binary mode...
// This detects the = sign, and then gets the previous numbers which should
// be the length of binary data
if ((val == '=' || val == ':') && inputBufferLength > 2) {
char[] chars = new char[2];
chars[0] = (char) inputBuffer[inputBufferLength - 3];
chars[1] = (char) inputBuffer[inputBufferLength - 2];
try {
binaryLength = Integer.parseInt(new String(chars), 16);
rxState = RxStateMachine.RECEIVE_BINARY;
} catch (NumberFormatException e) {
// Eat the exception
// This will occur when we have an '=' that's not part of a binary field
}
}
break;
case RECEIVE_BINARY:
inputBuffer[inputBufferLength++] = val;
if (--binaryLength == 0) {
rxState = RxStateMachine.RECEIVE_ASCII;
}
break;
default:
break;
}
}
return null;
}
/**
* Set the close flag to true.
*/
public void setClosing() {
this.closeHandler = true;
}
/**
* Requests parser thread to shutdown.
*/
public void close() {
setClosing();
try {
parserThread.interrupt();
parserThread.join();
} catch (InterruptedException e) {
logger.debug("Interrupted in packet parser thread shutdown join.");
}
logger.debug("TelegesisFrameHandler closed.");
}
/**
* Checks if parser thread is alive.
*
* @return true if parser thread is alive.
*/
public boolean isAlive() {
return parserThread != null && parserThread.isAlive();
}
// Synchronize this method so we can do the window check without interruption.
// Otherwise this method could be called twice from different threads that could end up with
// more than the TX_WINDOW number of frames sent.
private void sendNextFrame() {
synchronized (commandLock) {
// Are we already processing a command?
if (sentCommand != null) {
return;
}
TelegesisCommand nextFrame = sendQueue.poll();
if (nextFrame == null) {
// Nothing to send
stopTimer();
return;
}
logger.debug("TX Telegesis: {}", nextFrame);
// Remember the command we're processing
sentCommand = nextFrame;
// Send the data
StringBuilder builder = new StringBuilder();
for (int sendByte : nextFrame.serialize()) {
builder.append(String.format(" %02X", sendByte));
serialPort.write(sendByte);
}
logger.debug("TELEGESIS TX: Data{}", builder.toString());
// Start the timeout
startTimer();
}
}
/**
* Add a Telegesis command frame to the send queue. The sendQueue is a FIFO queue.
* This method queues a {@link TelegesisCommand} frame without waiting for a response.
*
* @param request {@link TelegesisFrame}
*/
public void queueFrame(TelegesisCommand request) {
sendQueue.add(request);
logger.debug("TX Telegesis queue: {}", sendQueue.size());
sendNextFrame();
}
/**
* Notify any transaction listeners when we receive a response.
*
* @param response the response data received
* @return true if the response was processed
*/
private boolean notifyTransactionComplete(final TelegesisCommand response) {
boolean processed = false;
logger.debug("Telegesis command complete: {}", response);
synchronized (transactionListeners) {
for (TelegesisListener listener : transactionListeners) {
try {
if (listener.transactionEvent(response)) {
processed = true;
}
} catch (Exception e) {
logger.debug("Exception processing Telegesis frame: {}: ", response, e);
}
}
}
return processed;
}
/**
* Sets the command timeout. This is the number of milliseconds to wait for a response from the stick once the
* command has been sent.
*
* @param commandTimeout
*/
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
/**
* Sets the transaction timeout. This is the number of milliseconds to wait for a response from the stick once the
* command has been initially queued.
*
* @param commandTimeout
*/
public void setTransactionTimeout(int transactionTimeout) {
this.transactionTimeout = transactionTimeout;
}
private void addTransactionListener(TelegesisListener listener) {
synchronized (transactionListeners) {
if (transactionListeners.contains(listener)) {
return;
}
transactionListeners.add(listener);
}
}
private void removeTransactionListener(TelegesisListener listener) {
synchronized (transactionListeners) {
transactionListeners.remove(listener);
}
}
/**
* Notify any event listeners when we receive an event.
*
* @param response the {@link TelegesisEvent} received
*/
private void notifyEventReceived(final TelegesisEvent event) {
logger.debug("Telegesis event received: {}", event);
synchronized (eventListeners) {
for (TelegesisEventListener listener : eventListeners) {
try {
listener.telegesisEventReceived(event);
} catch (Exception e) {
logger.debug("Exception processing Telegesis frame: {}: ", event, e);
}
}
}
}
public void addEventListener(TelegesisEventListener listener) {
synchronized (eventListeners) {
if (eventListeners.contains(listener)) {
return;
}
eventListeners.add(listener);
}
}
public void removeEventListener(TelegesisEventListener listener) {
synchronized (eventListeners) {
eventListeners.remove(listener);
}
}
/**
* Sends a Telegesis request to the NCP without waiting for the response.
*
* @param command Request {@link TelegesisCommand} to send
* @return response {@link Future} {@link TelegesisCommand}
*/
public Future<TelegesisCommand> sendRequestAsync(final TelegesisCommand command) {
class TransactionWaiter implements Callable<TelegesisCommand>, TelegesisListener {
private boolean complete = false;
@Override
public TelegesisCommand call() {
// Register a listener
addTransactionListener(this);
// Send the transaction
queueFrame(command);
// Wait for the transaction to complete
synchronized (this) {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
logger.debug(e.getMessage());
}
}
}
// Remove the listener
removeTransactionListener(this);
return null;// response;
}
@Override
public boolean transactionEvent(TelegesisCommand response) {
// Check if this response completes our transaction
if (!command.equals(response)) {
return false;
}
// response = request;
complete = true;
synchronized (this) {
notify();
}
return true;
}
}
Callable<TelegesisCommand> worker = new TransactionWaiter();
return executor.submit(worker);
}
/**
* Sends a Telegesis request to the dongle and waits for the response. The response is correlated with the request
* and the response data is available for the caller in the original command class.
*
* @param command Request {@link TelegesisCommand}
* @return response {@link TelegesisStatusCode} of the response, or null if there was a timeout
*/
public TelegesisStatusCode sendRequest(final TelegesisCommand command) {
Future<TelegesisCommand> future = sendRequestAsync(command);
try {
future.get(transactionTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.debug("Telegesis interrupted in sendRequest {}", command);
future.cancel(true);
return null;
}
return command.getStatus();
}
/**
* Sends a Telegesis request to the NCP without waiting for the response.
*
* @param command Request {@link TelegesisCommand} to send
* @return response {@link Future} {@link TelegesisCommand}
*/
public Future<TelegesisEvent> waitEventAsync(final Class<?> eventClass) {
class TransactionWaiter implements Callable<TelegesisEvent>, TelegesisEventListener {
private boolean complete = false;
private TelegesisEvent receivedEvent = null;
@Override
public TelegesisEvent call() {
// Register a listener
addEventListener(this);
// Wait for the event
synchronized (this) {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
logger.debug("Telegesis interrupted in waitEventAsync {}", eventClass);
}
}
}
// Remove the listener
removeEventListener(this);
return receivedEvent;
}
@Override
public void telegesisEventReceived(TelegesisEvent event) {
// Check if this response completes our transaction
if (event.getClass() != eventClass) {
return;
}
receivedEvent = event;
complete = true;
synchronized (this) {
notify();
}
}
}
Callable<TelegesisEvent> worker = new TransactionWaiter();
return executor.submit(worker);
}
/**
* Wait for the requested {@link TelegesisEvent} to occur
*
* @param eventClass the {@link TelegesisEvent} to wait for
* @return the {@link TelegesisEvent} once received, or null on exception
*/
public TelegesisEvent eventWait(final Class<?> eventClass) {
Future<TelegesisEvent> future = waitEventAsync(eventClass);
try {
return future.get(transactionTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.debug("Telegesis interrupted in eventWait {}", eventClass);
future.cancel(true);
return null;
}
}
/**
* Starts the transaction timeout. This will simply cancel the transaction and send the next frame from the queue if
* the timer times out. We don't try and retry as this might cause other unwanted issues.
*/
private void startTimer() {
stopTimer();
logger.trace("TELEGESIS Timer: Start");
timeoutTimer = timeoutScheduler.schedule(new Runnable() {
@Override
public void run() {
timeoutTimer = null;
logger.debug("TELEGESIS Timer: Timeout");
synchronized (commandLock) {
if (sentCommand != null) {
sentCommand = null;
sendNextFrame();
}
}
}
}, commandTimeout, TimeUnit.MILLISECONDS);
}
private void stopTimer() {
if (timeoutTimer != null) {
logger.trace("TELEGESIS Timer: Stop");
timeoutTimer.cancel(false);
timeoutTimer = null;
}
}
interface TelegesisListener {
boolean transactionEvent(TelegesisCommand response);
}
}
| com.zsmartsystems.zigbee.dongle.telegesis/src/main/java/com/zsmartsystems/zigbee/dongle/telegesis/internal/TelegesisFrameHandler.java | /**
* Copyright (c) 2016-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.dongle.telegesis.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisCommand;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisEvent;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisFrame;
import com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol.TelegesisStatusCode;
import com.zsmartsystems.zigbee.transport.ZigBeePort;
/**
* Frame parser for the Telegesis AT command protocol.
*
* @author Chris Jackson
*
*/
public class TelegesisFrameHandler {
/**
* The logger.
*/
private final Logger logger = LoggerFactory.getLogger(TelegesisFrameHandler.class);
/**
* The queue of {@link TelegesisFrame} frames waiting to be sent
*/
private final Queue<TelegesisCommand> sendQueue = new LinkedList<TelegesisCommand>();
private ExecutorService executor = Executors.newCachedThreadPool();
/**
* List of listeners waiting for commands to complete
*/
private final List<TelegesisListener> transactionListeners = new ArrayList<TelegesisListener>();
/**
* List of event listeners
*/
private final List<TelegesisEventListener> eventListeners = new ArrayList<TelegesisEventListener>();
/**
* The port.
*/
private ZigBeePort serialPort;
/**
* The parser parserThread.
*/
private Thread parserThread = null;
/**
* Object to synchronise access to sentCommand
*/
private Object commandLock = new Object();
/**
* The command that we're currently sending, or null if no command is being transacted
*/
private TelegesisCommand sentCommand = null;
/**
* Flag reflecting that parser has been closed and parser parserThread should exit.
*/
private boolean closeHandler = false;
/**
* Scheduler used as a timer to abort any transactions that don't complete in a timely manner
*/
private ScheduledExecutorService timeoutScheduler;
/**
* The future be used for timeouts
*/
private ScheduledFuture<?> timeoutTimer = null;
/**
* The maximum number of milliseconds to wait for the response from the stick
*/
private final int TRANSACTION_TIMEOUT = 500;
enum RxStateMachine {
WAITING,
RECEIVE_CMD,
RECEIVE_ASCII,
RECEIVE_BINARY
}
/**
* Construct which sets input stream where the packet is read from the and
* handler which further processes the received packet.
*
* @param serialPort the {@link ZigBeePort}
*/
public void start(final ZigBeePort serialPort) {
this.serialPort = serialPort;
this.timeoutScheduler = Executors.newSingleThreadScheduledExecutor();
parserThread = new Thread("TelegesisFrameHandler") {
@Override
public void run() {
logger.debug("TelegesisFrameHandler thread started");
while (!closeHandler) {
try {
// Get a packet from the serial port
int[] responseData = getPacket();
if (responseData == null) {
continue;
}
StringBuilder builder = new StringBuilder();
for (int value : responseData) {
builder.append(String.format(" %02X", value));
}
logger.debug("TELEGESIS RX: Data{}", builder.toString());
// Use the Event Factory to get an event
TelegesisEvent event = TelegesisEventFactory.getTelegesisFrame(responseData);
if (event != null) {
notifyEventReceived(event);
continue;
}
// If we're sending a command, then we need to process any responses
synchronized (commandLock) {
if (sentCommand != null) {
boolean done;
try {
done = sentCommand.deserialize(responseData);
} catch (Exception e) {
logger.debug("Exception deserialising frame {}. Transaction will complete. ",
builder.toString(), e);
done = true;
}
if (done) {
// Command completed
notifyTransactionComplete(sentCommand);
sentCommand = null;
sendNextFrame();
}
}
}
} catch (Exception e) {
logger.error("TelegesisFrameHandler exception", e);
}
}
logger.debug("TelegesisFrameHandler thread exited.");
}
};
parserThread.setDaemon(true);
parserThread.start();
}
private int[] getPacket() {
int[] inputBuffer = new int[120];
int inputBufferLength = 0;
RxStateMachine rxState = RxStateMachine.WAITING;
int binaryLength = 0;
logger.trace("TELEGESIS: Get Packet");
while (!closeHandler) {
int val = serialPort.read();
if (val == -1) {
// Timeout
continue;
}
if (inputBufferLength >= inputBuffer.length) {
// If we overrun the buffer, reset and go to WAITING mode
inputBufferLength = 0;
rxState = RxStateMachine.WAITING;
logger.debug("TELEGESIS RX buffer overrun - resetting!");
}
logger.trace("TELEGESIS RX: {}", String.format("%02X %c", val, val));
switch (rxState) {
case WAITING:
// Ignore any CR and LF
if (val == '\n' || val == '\r') {
continue;
}
inputBuffer[inputBufferLength++] = val;
rxState = RxStateMachine.RECEIVE_CMD;
break;
case RECEIVE_CMD:
if (val == '\n' || val == '\r') {
// We're done
// Return the packet without the CRLF on the end
return Arrays.copyOfRange(inputBuffer, 0, inputBufferLength);
}
// Here we wait for the colon
// This allows us to avoid switching into binary mode for ATS responses
inputBuffer[inputBufferLength++] = val;
if (val == ':') {
rxState = RxStateMachine.RECEIVE_ASCII;
}
break;
case RECEIVE_ASCII:
if (val == '\n' || val == '\r') {
// We're done
// Return the packet without the CRLF on the end
return Arrays.copyOfRange(inputBuffer, 0, inputBufferLength);
}
inputBuffer[inputBufferLength++] = val;
// Handle switching to binary mode...
// This detects the = sign, and then gets the previous numbers which should
// be the length of binary data
if ((val == '=' || val == ':') && inputBufferLength > 2) {
char[] chars = new char[2];
chars[0] = (char) inputBuffer[inputBufferLength - 3];
chars[1] = (char) inputBuffer[inputBufferLength - 2];
try {
binaryLength = Integer.parseInt(new String(chars), 16);
rxState = RxStateMachine.RECEIVE_BINARY;
} catch (NumberFormatException e) {
// Eat the exception
// This will occur when we have an '=' that's not part of a binary field
}
}
break;
case RECEIVE_BINARY:
inputBuffer[inputBufferLength++] = val;
if (--binaryLength == 0) {
rxState = RxStateMachine.RECEIVE_ASCII;
}
break;
default:
break;
}
}
return null;
}
/**
* Set the close flag to true.
*/
public void setClosing() {
this.closeHandler = true;
}
/**
* Requests parser thread to shutdown.
*/
public void close() {
setClosing();
try {
parserThread.interrupt();
parserThread.join();
} catch (InterruptedException e) {
logger.debug("Interrupted in packet parser thread shutdown join.");
}
logger.debug("TelegesisFrameHandler closed.");
}
/**
* Checks if parser thread is alive.
*
* @return true if parser thread is alive.
*/
public boolean isAlive() {
return parserThread != null && parserThread.isAlive();
}
// Synchronize this method so we can do the window check without interruption.
// Otherwise this method could be called twice from different threads that could end up with
// more than the TX_WINDOW number of frames sent.
private void sendNextFrame() {
synchronized (commandLock) {
// Are we already processing a command?
if (sentCommand != null) {
return;
}
TelegesisCommand nextFrame = sendQueue.poll();
if (nextFrame == null) {
// Nothing to send
stopTimer();
return;
}
logger.trace("TX Telegesis: {}", nextFrame);
// Remember the command we're processing
sentCommand = nextFrame;
// Send the data
StringBuilder builder = new StringBuilder();
for (int sendByte : nextFrame.serialize()) {
builder.append(String.format(" %02X", sendByte));
serialPort.write(sendByte);
}
logger.debug("TELEGESIS TX: Data{}", builder.toString());
// Start the timeout
startTimer();
}
}
/**
* Add a Telegesis command frame to the send queue. The sendQueue is a FIFO queue.
* This method queues a {@link TelegesisCommand} frame without waiting for a response.
*
* @param request {@link TelegesisFrame}
*/
public void queueFrame(TelegesisCommand request) {
sendQueue.add(request);
logger.debug("TX Telegesis queue: {}", sendQueue.size());
if (sendQueue.size() > 2) {
sentCommand = null;
}
sendNextFrame();
}
/**
* Notify any transaction listeners when we receive a response.
*
* @param response the response data received
* @return true if the response was processed
*/
private boolean notifyTransactionComplete(final TelegesisCommand response) {
boolean processed = false;
logger.debug("Telegesis command complete: {}", response);
synchronized (transactionListeners) {
for (TelegesisListener listener : transactionListeners) {
try {
if (listener.transactionEvent(response)) {
processed = true;
}
} catch (Exception e) {
logger.debug("Exception processing Telegesis frame: {}: ", response, e);
}
}
}
return processed;
}
private void addTransactionListener(TelegesisListener listener) {
synchronized (transactionListeners) {
if (transactionListeners.contains(listener)) {
return;
}
transactionListeners.add(listener);
}
}
private void removeTransactionListener(TelegesisListener listener) {
synchronized (transactionListeners) {
transactionListeners.remove(listener);
}
}
/**
* Notify any event listeners when we receive an event.
*
* @param response the {@link TelegesisEvent} received
*/
private void notifyEventReceived(final TelegesisEvent event) {
logger.debug("Telegesis event received: {}", event);
synchronized (eventListeners) {
for (TelegesisEventListener listener : eventListeners) {
try {
listener.telegesisEventReceived(event);
} catch (Exception e) {
logger.debug("Exception processing Telegesis frame: {}: ", event, e);
}
}
}
}
public void addEventListener(TelegesisEventListener listener) {
synchronized (eventListeners) {
if (eventListeners.contains(listener)) {
return;
}
eventListeners.add(listener);
}
}
public void removeEventListener(TelegesisEventListener listener) {
synchronized (eventListeners) {
eventListeners.remove(listener);
}
}
/**
* Sends a Telegesis request to the NCP without waiting for the response.
*
* @param command
* Request {@link TelegesisCommand} to send
* @return response {@link Future} {@link TelegesisCommand}
*/
public Future<TelegesisCommand> sendRequestAsync(final TelegesisCommand command) {
class TransactionWaiter implements Callable<TelegesisCommand>, TelegesisListener {
private boolean complete = false;
@Override
public TelegesisCommand call() {
// Register a listener
addTransactionListener(this);
// Send the transaction
queueFrame(command);
// Wait for the transaction to complete
synchronized (this) {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
logger.debug(e.getMessage());
}
}
}
// Remove the listener
removeTransactionListener(this);
return null;// response;
}
@Override
public boolean transactionEvent(TelegesisCommand response) {
// Check if this response completes our transaction
if (!command.equals(response)) {
return false;
}
// response = request;
complete = true;
synchronized (this) {
notify();
}
return true;
}
}
Callable<TelegesisCommand> worker = new TransactionWaiter();
return executor.submit(worker);
}
/**
* Sends a Telegesis request to the dongle and waits for the response. The response is correlated with the request
* and the response data is available for the caller in the original command class.
*
* @param command
* Request {@link TelegesisCommand}
* @return response {@link TelegesisStatusCode} of the response, or null if there was a timeout
*/
public TelegesisStatusCode sendRequest(final TelegesisCommand command) {
Future<TelegesisCommand> future = sendRequestAsync(command);
try {
future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
return null;
}
return command.getStatus();
}
/**
* Sends a Telegesis request to the NCP without waiting for the response.
*
* @param command
* Request {@link TelegesisCommand} to send
* @return response {@link Future} {@link TelegesisCommand}
*/
public Future<TelegesisEvent> waitEventAsync(final Class<?> eventClass) {
class TransactionWaiter implements Callable<TelegesisEvent>, TelegesisEventListener {
private boolean complete = false;
private TelegesisEvent receivedEvent = null;
@Override
public TelegesisEvent call() {
// Register a listener
addEventListener(this);
// Wait for the event
synchronized (this) {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
logger.debug(e.getMessage());
}
}
}
// Remove the listener
removeEventListener(this);
return receivedEvent;
}
@Override
public void telegesisEventReceived(TelegesisEvent event) {
// Check if this response completes our transaction
if (event.getClass() != eventClass) {
return;
}
receivedEvent = event;
complete = true;
synchronized (this) {
notify();
}
}
}
Callable<TelegesisEvent> worker = new TransactionWaiter();
return executor.submit(worker);
}
/**
* Wait for the requested {@link TelegesisEvent} to occur
*
* @param eventClass the {@link TelegesisEvent} to wait for
* @return the {@link TelegesisEvent} once received, or null on exception
*/
public TelegesisEvent eventWait(final Class<?> eventClass) {
Future<TelegesisEvent> future = waitEventAsync(eventClass);
try {
return future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
return null;
}
}
/**
* Starts the transaction timeout. This will simply cancel the transaction and send the next frame from the queue if
* the timer times out. We don't try and retry as this might cause other unwanted issues.
*/
private void startTimer() {
stopTimer();
logger.trace("TELEGESIS Timer: Start");
timeoutTimer = timeoutScheduler.schedule(new Runnable() {
@Override
public void run() {
timeoutTimer = null;
logger.debug("TELEGESIS Timer: Timeout");
synchronized (commandLock) {
if (sentCommand != null) {
sentCommand = null;
sendNextFrame();
}
}
}
}, TRANSACTION_TIMEOUT, TimeUnit.MILLISECONDS);
}
private void stopTimer() {
if (timeoutTimer != null) {
logger.trace("TELEGESIS Timer: Stop");
timeoutTimer.cancel(false);
timeoutTimer = null;
}
}
interface TelegesisListener {
boolean transactionEvent(TelegesisCommand response);
}
}
| Improve debug logging in Telegesis handler (#177)
Signed-off-by: Chris Jackson <[email protected]> | com.zsmartsystems.zigbee.dongle.telegesis/src/main/java/com/zsmartsystems/zigbee/dongle/telegesis/internal/TelegesisFrameHandler.java | Improve debug logging in Telegesis handler (#177) | <ide><path>om.zsmartsystems.zigbee.dongle.telegesis/src/main/java/com/zsmartsystems/zigbee/dongle/telegesis/internal/TelegesisFrameHandler.java
<ide> private ScheduledFuture<?> timeoutTimer = null;
<ide>
<ide> /**
<del> * The maximum number of milliseconds to wait for the response from the stick
<del> */
<del> private final int TRANSACTION_TIMEOUT = 500;
<add> * The maximum number of milliseconds to wait for the response from the stick once the request was sent
<add> */
<add> private final int DEFAULT_TRANSACTION_TIMEOUT = 500;
<add>
<add> /**
<add> * The maximum number of milliseconds to wait for the completion of the transaction after it's queued
<add> */
<add> private final int DEFAULT_COMMAND_TIMEOUT = 10000;
<add>
<add> private int transactionTimeout = DEFAULT_TRANSACTION_TIMEOUT;
<add>
<add> private int commandTimeout = DEFAULT_COMMAND_TIMEOUT;
<ide>
<ide> enum RxStateMachine {
<ide> WAITING,
<ide> return;
<ide> }
<ide>
<del> logger.trace("TX Telegesis: {}", nextFrame);
<add> logger.debug("TX Telegesis: {}", nextFrame);
<ide>
<ide> // Remember the command we're processing
<ide> sentCommand = nextFrame;
<ide> sendQueue.add(request);
<ide>
<ide> logger.debug("TX Telegesis queue: {}", sendQueue.size());
<del>
<del> if (sendQueue.size() > 2) {
<del> sentCommand = null;
<del> }
<ide>
<ide> sendNextFrame();
<ide> }
<ide> }
<ide>
<ide> return processed;
<add> }
<add>
<add> /**
<add> * Sets the command timeout. This is the number of milliseconds to wait for a response from the stick once the
<add> * command has been sent.
<add> *
<add> * @param commandTimeout
<add> */
<add> public void setCommandTimeout(int commandTimeout) {
<add> this.commandTimeout = commandTimeout;
<add> }
<add>
<add> /**
<add> * Sets the transaction timeout. This is the number of milliseconds to wait for a response from the stick once the
<add> * command has been initially queued.
<add> *
<add> * @param commandTimeout
<add> */
<add> public void setTransactionTimeout(int transactionTimeout) {
<add> this.transactionTimeout = transactionTimeout;
<ide> }
<ide>
<ide> private void addTransactionListener(TelegesisListener listener) {
<ide> /**
<ide> * Sends a Telegesis request to the NCP without waiting for the response.
<ide> *
<del> * @param command
<del> * Request {@link TelegesisCommand} to send
<add> * @param command Request {@link TelegesisCommand} to send
<ide> * @return response {@link Future} {@link TelegesisCommand}
<ide> */
<ide> public Future<TelegesisCommand> sendRequestAsync(final TelegesisCommand command) {
<ide> * Sends a Telegesis request to the dongle and waits for the response. The response is correlated with the request
<ide> * and the response data is available for the caller in the original command class.
<ide> *
<del> * @param command
<del> * Request {@link TelegesisCommand}
<add> * @param command Request {@link TelegesisCommand}
<ide> * @return response {@link TelegesisStatusCode} of the response, or null if there was a timeout
<ide> */
<ide> public TelegesisStatusCode sendRequest(final TelegesisCommand command) {
<ide> Future<TelegesisCommand> future = sendRequestAsync(command);
<ide> try {
<del> future.get(10, TimeUnit.SECONDS);
<add> future.get(transactionTimeout, TimeUnit.MILLISECONDS);
<ide> } catch (InterruptedException | ExecutionException | TimeoutException e) {
<add> logger.debug("Telegesis interrupted in sendRequest {}", command);
<add> future.cancel(true);
<ide> return null;
<ide> }
<ide>
<ide> /**
<ide> * Sends a Telegesis request to the NCP without waiting for the response.
<ide> *
<del> * @param command
<del> * Request {@link TelegesisCommand} to send
<add> * @param command Request {@link TelegesisCommand} to send
<ide> * @return response {@link Future} {@link TelegesisCommand}
<ide> */
<ide> public Future<TelegesisEvent> waitEventAsync(final Class<?> eventClass) {
<ide> try {
<ide> wait();
<ide> } catch (InterruptedException e) {
<del> logger.debug(e.getMessage());
<add> logger.debug("Telegesis interrupted in waitEventAsync {}", eventClass);
<ide> }
<ide> }
<ide> }
<ide> public TelegesisEvent eventWait(final Class<?> eventClass) {
<ide> Future<TelegesisEvent> future = waitEventAsync(eventClass);
<ide> try {
<del> return future.get(10, TimeUnit.SECONDS);
<add> return future.get(transactionTimeout, TimeUnit.MILLISECONDS);
<ide> } catch (InterruptedException | ExecutionException | TimeoutException e) {
<add> logger.debug("Telegesis interrupted in eventWait {}", eventClass);
<add> future.cancel(true);
<ide> return null;
<ide> }
<ide> }
<ide> }
<ide> }
<ide> }
<del> }, TRANSACTION_TIMEOUT, TimeUnit.MILLISECONDS);
<add> }, commandTimeout, TimeUnit.MILLISECONDS);
<ide> }
<ide>
<ide> private void stopTimer() { |
|
Java | agpl-3.0 | f23177c733d4dd0557e87c7b17027023a8a22cee | 0 | veronikaslc/phenotips,itaiGershtansky/phenotips,danielpgross/phenotips,phenotips/phenotips,DeanWay/phenotips,mjshepherd/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,phenotips/phenotips,tmarathe/phenotips,teyden/phenotips,phenotips/phenotips,DeanWay/phenotips,DeanWay/phenotips,alexhenrie/phenotips,teyden/phenotips,JKereliuk/phenotips,phenotips/phenotips,mjshepherd/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,teyden/phenotips,teyden/phenotips,itaiGershtansky/phenotips,danielpgross/phenotips,mjshepherd/phenotips,phenotips/phenotips,JKereliuk/phenotips,JKereliuk/phenotips,tmarathe/phenotips,tmarathe/phenotips,itaiGershtansky/phenotips,teyden/phenotips,danielpgross/phenotips | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
*/
package org.phenotips.data.test.po;
import org.xwiki.test.ui.po.BaseElement;
import org.xwiki.test.ui.po.InlinePage;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
/**
* Represents the actions possible on a patient record in view mode.
*
* @version $Id$
* @since 1.0RC1
*/
public class PatientRecordEditPage extends InlinePage
{
@FindBy(css = "#document-title h1")
private WebElement recordId;
@FindBy(id = "HFamilyhistoryandpedigree")
WebElement familyHistorySectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_maternal_ethnicity_2")
WebElement maternalEthnicity;
@FindBy(id = "PhenoTips.PatientClass_0_paternal_ethnicity_2")
WebElement paternalEthnicity;
@FindBy(id = "HPrenatalandperinatalhistory")
WebElement prenatalAndPerinatalHistorySectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_family_history")
WebElement familyHealthConditions;
@FindBy(css = ".fieldset.gestation input[type=\"text\"]")
WebElement gestationAtDelivery;
@FindBy(id = "HMedicalhistory")
WebElement medicalHistorySectionHeading;
@FindBy(id = "HMeasurements")
WebElement measurementsSectionHeading;
@FindBy(css = ".measurement-info.chapter .list-actions a.add-data-button")
WebElement newEntryMeasurements;
/* MEASUREMENT ELEMENTS */
@FindBy(id = "PhenoTips.MeasurementsClass_0_weight")
WebElement measurementWeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_height")
WebElement measurementHeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_armspan")
WebElement measurementArmSpan;
@FindBy(id = "PhenoTips.MeasurementsClass_0_sitting")
WebElement measurementSittingHeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hc")
WebElement measurementHeadCircumference;
@FindBy(id = "PhenoTips.MeasurementsClass_0_philtrum")
WebElement measurementPhiltrumLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ear")
WebElement measurementLeftEarLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ear_right")
WebElement measurementRightEarLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ocd")
WebElement measurementOuterCanthalDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_icd")
WebElement measurementInnerCanthalDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_pfl")
WebElement measurementPalpebralFissureLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ipd")
WebElement measurementInterpupilaryDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hand")
WebElement measurementLeftHandLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_palm")
WebElement measurementLeftPalmLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_foot")
WebElement measurementLeftFootLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hand_right")
WebElement measurementRightHandLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_palm_right")
WebElement measurementRightPalmLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_foot_right")
WebElement measurementRightFootLength;
@FindBy(id = "HGenotypeinformation")
WebElement genotypeInformationSectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_unaffected")
WebElement patientIsClinicallyNormal;
@FindBy(id = "HDiagnosis")
WebElement diagnosisSectionHeading;
//
@FindBy(id = "PhenoTips.PatientClass_0_diagnosis_notes")
WebElement diagnosisAdditionalComments;
@FindBy(id = "result__270400")
WebElement smithLemliOptizSyndrome;
@FindBy(id = "result__193520")
WebElement watsonSyndrome;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[@class = 'tool'][text() = 'Add details']")
WebElement hemihypertrophyAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[contains(@class, 'age_of_onset')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement ageOfOnsetHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//dd[@class = 'age_of_onset']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0003623']]//*[@value = 'HP:0003623']")
WebElement neonatalOnsetHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[contains(@class, 'temporal_pattern')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement temporalPatternHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//dd[@class = 'temporal_pattern']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0011011']]//*[@value = 'HP:0011011']")
WebElement subacuteTemporalPatternHemihypertrophy;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000175']]//*[@class = 'tool'][text() = 'Delete']")
WebElement deleteCleftPalate;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001999']]//*[@class = 'tool'][text() = 'Add details']")
WebElement abnormalFacialShapeAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001999']]//*[contains(@class, 'pace_of_progression')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement paceOfProgressionAbnormalFacialShape;
@FindBy(id = "PhenoTips.PhenotypeMetaClass_1_pace_of_progression_HP:0003677")
WebElement slowPaceOfProgressionAbnormalFacialShape;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[@class = 'tool'][text() = 'Add details']")
WebElement hypotelorismAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[contains(@class, 'severity')]//*[@class = 'collapse-button'][text() = '►']")
WebElement severityHypotelorism;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//dd[@class = 'severity']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012826']]//*[@value = 'HP:0012826']")
WebElement moderateSeverityHypotelorism;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000359']]//*[@class = 'tool'][text() = 'Add details']")
WebElement abnormalityOfTheInnerEarAddDetails;
@FindBy(xpath = "//*[@class = 'group-contents'][.//input[@value = 'HP:0000359']]//*[contains(@class, 'spatial_pattern')]//*[@class = 'collapse-button'][text() = '►']")
WebElement spatialPatternAbnormalityOfTheInnerEar;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000359']]//dd[@class = 'spatial_pattern']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012839']]//*[@value = 'HP:0012839']")
WebElement distalSpatialPatternAbnormalityOfTheInnerEar;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0011675']]//*[@class = 'tool'][text() = 'Add details']")
WebElement arrhythmiaAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0011675']]//dd[@class = 'comments']//textarea[contains(@name, 'PhenoTips.PhenotypeMetaClass')]")
WebElement arrhythmiaComments;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//*[@class = 'tool'][text() = 'Add details']")
WebElement scoliosisAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//*[contains(@class, 'laterality')]//*[@class = 'collapse-button'][text() = '►']")
WebElement lateralityScoliosis;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//dd[@class = 'laterality']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012834']]//*[@value = 'HP:0012834']")
WebElement rightLateralityScoliosis;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//*[@class = 'tool'][text() = 'Add details']")
WebElement seizuresAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//*[contains(@class, 'severity')]//*[@class = 'collapse-button'][text() = '►']")
WebElement severitySeizures;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//dd[@class = 'severity']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012825']]//*[@value = 'HP:0012825']")
WebElement mildSeveritySeizures;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010722']]")
WebElement asymmetryOfTheEarsYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]")
WebElement immunodeficiencyYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]")
WebElement abnormalityOfTheCartoidArteriesYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[@class = 'yes'][.//input[@value = 'HP:0010297']]")
WebElement bifidTongueYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'yes')][.//input[@value = 'HP:0002591']]")
WebElement polyphagiaYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'yes')][.//input[@value = 'HP:0000892']]")
WebElement bifidRibsYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'no')][.//input[@value = 'HP:0002521']]")
WebElement hypsarrhythmiaNO;
@FindBy(xpath = "//*[contains(@class, 'term-entry')][.//label[text() = 'Coarctation of aorta']]/span[@class = 'expand-tool']")
WebElement coarctationOfAortaDropDown;
@FindBy(xpath = "//*[contains(@class, 'entry')]//*[contains(@class, 'info')][.//*[text() = 'Coarctation of abdominal aorta']]//*[@class = 'value']")
WebElement checkCoarctationOfAortaDropDown;
@FindBy(id = "quick-phenotype-search")
WebElement phenotypeQuickSearch;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0000518']]")
WebElement quickSearchCataractYes;
@FindBy(id = "PhenoTips.PatientClass_0_indication_for_referral")
WebElement indicationForReferral;
@FindBy(xpath = "//*[@class = 'prenatal_phenotype-other custom-entries'][//*[contains(@class, 'suggested')]]//*[contains(@class, 'suggested')]")
WebElement prenatalGrowthPatternsOther;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0003612']]")
WebElement positiveFerricChlorideTestYes;
@FindBy(xpath = "//*[@class = 'prenatal_phenotype-group'][.//*[@id = 'HPrenatal-development-or-birth']]//*[contains(@class, 'prenatal_phenotype-other')][//*[contains(@class, 'suggested')]]//*[contains(@class, 'suggested')]")
WebElement prenatalDevelopmentOrBirthOther;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][.//input[@value = 'HP:0008733']]")
WebElement dysplasticTestesYes;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'weight_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement weightPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'height_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement heightPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'bmi_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement bmiPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'sitting_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement sittingPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'hc_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement headCircumferencePctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'philtrum_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement philtrumPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ear_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftEarPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ear_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightEarPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ocd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement outerCanthalPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'icd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement innerCanthalPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'pfl_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement palpebralFissurePctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ipd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement interpupilaryPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'palm_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftPalmPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'foot_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftFootPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'palm_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightPalmPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'foot_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightFootPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'bmi']//*[contains(@class, 'displayed-value')]")
WebElement bmiNumber;
@FindBy(id = "PhenoTips.PatientClass_0_omim_id")
WebElement OMIMDisorderBar;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'suggestValue'][text() = '#194190 WOLF-HIRSCHHORN SYNDROME']")
WebElement OMIMDisorderWolfSyndrome;
@FindBy(xpath = "//*[@class = 'ncbi-search-box']//*[@id = 'defaultSearchTerms']//*[@class = 'search-term symptom'][text() = 'Lower limb undergrowth']")
WebElement OMIMBoxLowerLimbUnderGrowth;
@FindBy(xpath = "//*[@class = 'ncbi-search-box']//*[@id = 'defaultSearchTerms']//*[@class = 'search-term symptom disabled'][text() = 'Lower limb undergrowth']")
WebElement OMIMBoxLowerLimbUnderGrowthExcluded;
@FindBy(xpath = "//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][.//input[@value = '270400']]//*[@class = 'value'][text()='#270400 SMITH-LEMLI-OPITZ SYNDROME']")
WebElement checkSmithLemliInOMIM;
@FindBy(id = "result__123450")
WebElement criDuChatSyndrome;
@FindBy(xpath = "//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][.//input[@value = '123450']]//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']")
WebElement checkCriDuChatAppears;
@FindBy(id = "PhenoTips.PatientClass_0_omim_id_123450")
WebElement criDuChatOMIMTop;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000639']]//*[@class = 'tool'][text() = 'Delete']")
WebElement deleteNystagmusRight;
@FindBy(xpath = "//*[@class = 'resultContainer']//li[contains(@class, 'xitem')]//*[contains(@class, 'xTooltip')]//*[contains(text(), 'Browse related terms')]")
WebElement browseRelatedTermsCataract;
@FindBy(xpath = "//*[@class = 'entry-data'][.//*[contains(@class, 'yes-no-picker')]][.//*[@value = 'HP:0000517']]//*[@class = 'value'][text() = 'Abnormality of the lens']")
WebElement abnormalityOfTheLensGoUp;
@FindBy(xpath = "//*[@class = 'entry-data'][.//*[contains(@class, 'yes-no-picker')]][.//*[@value = 'HP:0004328']]//*[@class = 'value'][text() = 'Abnormality of the anterior segment of the eye']")
WebElement abnormalityOfTheAnteriorSegmentOfTheEyeCheck;
@FindBy(xpath = "//*[contains(@class, 'msdialog-modal-container')]//*[@class = 'msdialog-box']//*[@class = 'msdialog-close']")
WebElement closeBrowseRelatedTerms;
@FindBy(xpath = "//*[contains(@class, 'entry descendent')][.//span[contains(@class, 'yes-no-picker')]][.//label[@class = 'yes']][.//input[@value = 'HP:0012629']]//*[contains(@class, 'yes-no-picker')]//*[@class = 'yes']")
WebElement phacodonesisYes;
@FindBy(xpath = "//*[contains(@class, 'suggestItems')]//*[@class = 'hide-button-wrapper']//*[@class = 'hide-button']")
WebElement hideQuickSearchBarSuggestions;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[@class = 'month']")
WebElement setMonthDate;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[contains(@class, 'cds_body')]//td[.//div[text() = '1']][1]")
WebElement date1;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[contains(@class, 'cds_body')]//td[.//div[text() = '12']][1]")
WebElement date12;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[contains(@class, 'phenotype-info')]")
WebElement moreInfoHypotelorism;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[@class = 'xTooltip']//*[@class = 'value']")
WebElement checkMoreInfoHypotelorismOpened;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoHypotelorism;
@FindBy(xpath = "//*[@class = 'fieldset gender gender']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoSex;
@FindBy(xpath = "//*[contains(@class, 'patient-info')]//*[contains(@class, 'gender')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoSex;
@FindBy(xpath = "//*[contains(@class, 'patient-info')]//*[contains(@class, 'gender')]//*[@class = 'xTooltip']//span[@class = 'hide-tool']")
WebElement closeMoreInfoSex;
@FindBy(css = ".indication_for_referral .xHelpButton")
WebElement moreInfoIndicationForReferral;
@FindBy(css = ".indication_for_referral .xTooltip > div")
WebElement checkMoreInfoIndicationForReferral;
@FindBy(css = ".indication_for_referral .xTooltip .hide-tool")
WebElement closeMoreInfoIndicationForReferral;
@FindBy(css = ".relatives-info .xHelpButton")
WebElement moreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .xTooltip > div")
WebElement checkMoreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .xTooltip .hide-tool")
WebElement closeMoreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .list-actions .add-data-button")
WebElement newEntryFamilyStudy;
@FindBy(id = "PhenoTips.RelativeClass_0_relative_type")
WebElement thisPatientIsThe;
@FindBy(xpath = "//*[contains(@class, 'relatives-info')]//*[@class = 'relative_of']//*[@class = 'suggested']")
WebElement ofPatientWithIdentifier;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[@class = 'xTooltip']")
WebElement checkMoreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[@class = 'xTooltip']")
WebElement checkMoreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoOMIMDisorder;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoOMIMDisorder;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoOMIMDisorder;
@FindBy(id = "HYoumaywanttoinvestigate...")
WebElement youMayWantToInvestigate;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'unaffected controller')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'unaffected controller')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[@class = 'browse-phenotype-categories']//*[@class = 'expand-tools'][@class = 'collapse-all']//*[@class = 'collapse-all']")
WebElement collapseAllPhenotypes;
@FindBy(xpath = "//*[@class = 'browse-phenotype-categories']//*[@class = 'expand-tools'][@class = 'collapse-all']//*[@class = 'expand-all']")
WebElement expandAllPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']")
WebElement chartTitleBoys;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, girls']")
WebElement chartTitleGirls;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, 2 to 20 years, boys']")
WebElement chartTitleOlderBoys;
@FindBy(id = "PhenoTips.MeasurementsClass_0_date")
WebElement dateOfMeasurments;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'age']//*[@class = 'age displayed-value']")
WebElement getAgeMeasurements;
@FindBy(xpath = "//*[@class = 'bottombuttons']//*[@class = 'button'][@name = 'action_save']")
WebElement saveAndViewButton;
@FindBy(xpath = "//*[@class = 'bottombuttons']//*[@class = 'button'][@name = 'action_saveandcontinue']")
WebElement saveAndContinueButton;
@FindBy(xpath = "//*[contains(@class, 'maternal_ethnicity')]//*[@class = 'hint']")
WebElement checkFamilyHistoryExpanded;
@FindBy(xpath = "//*[contains(@class, 'assistedReproduction_fertilityMeds ')]//*[@class = 'yes']")
WebElement assistedReproductionFertilityMedsYes;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']")
WebElement checkIfGrowthChartsAreShowingByText;
// MINE
@FindBy(id = "PhenoTips.PatientClass_0_external_id")
WebElement patientIdentifier;
@FindBy(id = "body")
WebElement body;
/* Date of Birth */
/* Date of Death */
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[@class = 'year']")
WebElement setYearDateOfBirth;
@FindBy(css = ".fieldset.date_of_birth .fuzzy-date-picker")
WebElement birthDateSelector;
@FindBy(css = ".fieldset.date_of_death .fuzzy-date-picker")
WebElement deathDateSelector;
@FindBy(id = "PhenoTips.PatientClass_0_last_name")
WebElement patientLastName;
@FindBy(id = "PhenoTips.PatientClass_0_first_name")
WebElement patientFirstName;
@FindBy(id = "xwiki-form-gender-0-0")
WebElement patientGenderMale;
@FindBy(id = "xwiki-form-gender-0-1")
WebElement patientGenderFemale;
@FindBy(id = "xwiki-form-gender-0-2")
WebElement patientGenderOther;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0003745")
WebElement globalInheritanceSporadic;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0000006")
WebElement globalInheritanceAutosomal;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0010982")
WebElement globalInheritancePolygenic;
@FindBy(id = "PhenoTips.PatientClass_0_gestation_term")
WebElement checkTermBirth;
// Assisted Reproduction
@FindBy(css = ".fieldset.assistedReproduction_fertilityMeds label.yes")
WebElement assistedReproductionFertilityYes;
@FindBy(css = ".fieldset.ivf label.no")
WebElement assistedReproductionInVitroNo;
// APGAR Scores
@FindBy(id = "PhenoTips.PatientClass_0_apgar1")
WebElement APGAROneMinute;
@FindBy(id = "PhenoTips.PatientClass_0_apgar5")
WebElement APGARFiveMinutes;
@FindBy(id = "PhenoTips.PatientClass_0_prenatal_development")
WebElement prenatalNotes;
@FindBy(id = "PhenoTips.PatientClass_0_prenatal_phenotype_HP:0001518")
WebElement prenatalGrowthSmallGestationalYes;
@FindBy(css = "label.yes[for=\"PhenoTips.PatientClass_0_prenatal_phenotype_HP:0003517\"]")
WebElement prenatalGrowthLargeBirthYes;
@FindBy(css = ".prenatal_phenotype-group #HPrenatal-growth-parameters ~ .prenatal_phenotype-other input.suggested")
WebElement prenatalGrowthOther;
@FindBy(css = "label.no[for=\"PhenoTips.PatientClass_0_negative_prenatal_phenotype_HP:0001561\"]")
WebElement prenatalDevelopmentPolyhydramniosNo;
@FindBy(css = ".prenatal_phenotype-group #HPrenatal-development-or-birth ~ .prenatal_phenotype-other input.suggested")
WebElement prenatalDevelopmentOther;
@FindBy(id = "PhenoTips.PatientClass_0_global_age_of_onset_HP:0003584")
WebElement lateOnset;
@FindBy(id = "PhenoTips.PatientClass_0_medical_history")
WebElement medicalHistory;
@FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular td.gene input[name=\"PhenoTips.InvestigationClass_0_gene\"]")
WebElement geneCandidateSearch;
@FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular td.comments textarea[name=\"PhenoTips.InvestigationClass_0_comments\"]")
WebElement geneCandidateComment;
@FindBy(css = ".chapter.genotype #extradata-list-PhenoTips\\2e InvestigationClass-molecular + .list-actions .add-data-button")
WebElement newEntryListOfCandidateGenes;
@FindBy(css = "#extradata-list-PhenoTips\\2e RejectedGenesClass > tbody > tr.new > td.gene > input")
WebElement genePreviously;
@FindBy(css = "#PhenoTips\\2e RejectedGenesClass_1_comments")
WebElement genePreviouslyTestedComment;
@FindBy(css = ".chapter.genotype #extradata-list-PhenoTips\\2e RejectedGenesClass + .list-actions .add-data-button")
WebElement newEntryPreviouslyTested;
@FindBy(id = "HCaseresolution")
WebElement caseResolutionSectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_solved")
WebElement caseSolved;
@FindBy(css = ".phenotype-info.chapter.collapsed > .expand-tools .show .tool")
WebElement clinicalSymptomsAndPhysicalFindings;
@FindBy(id = "PhenoTips.PatientClass_0_solved__pubmed_id")
WebElement pubmedID;
@FindBy(css = ".fieldset.solved__gene_id input.suggested")
WebElement geneID;
@FindBy(id = "PhenoTips.PatientClass_0_solved__notes")
WebElement resolutionNotes;
@FindBy(css = ".bottombuttons input[name=\"action_save\"]")
WebElement saveAndViewSummary;
public static PatientRecordEditPage gotoPage(String patientId)
{
getUtil().gotoPage("data", patientId, "edit");
return new PatientRecordEditPage();
}
public void clickBody()
{
this.body.click();
}
public String getPatientRecordId()
{
return this.recordId.getText();
}
/* PATIENT INFORMATION */
/**
* Sets the first and last name of the patient
*
* @param first patient first name
* @param last patient last name
*/
public void setPatientName(String first, String last)
{
// first name
this.patientLastName.clear();
this.patientLastName.sendKeys(first);
// last name
this.patientFirstName.clear();
this.patientFirstName.sendKeys(last);
}
/**
* Sets the full birthdate of the patient
*
* @param day the birthdate of the patient
* @param month the birthmonth of the patient
* @param year the birthyear of the patient
*/
public void setPatientDateOfBirth(String day, String month, String year)
{
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(1) > select")))
.selectByVisibleText(year);
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(2) > select")))
.selectByVisibleText(month);
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(3) > select")))
.selectByVisibleText(day);
}
/**
* Sets the date of passing of the patient
*
* @param day the day of death of the patient
* @param month the month death of the patient
* @param year the year death of the patient
*/
public void setPatientDateOfDeath(String day, String month, String year)
{
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(1) > select")))
.selectByVisibleText(year);
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(2) > select")))
.selectByVisibleText(month);
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(3) > select")))
.selectByVisibleText(day);
}
/**
* Sets the gender of the patient
*
* @param gender one of {@code male}, {@code female} or {@code other}
*/
public void setPatientGender(String gender)
{
if (gender == "male") {
this.patientGenderMale.click();
} else if (gender == "female") {
this.patientGenderFemale.click();
} else if (gender == "other") {
this.patientGenderOther.click();
}
this.body.click();
}
public void expandFamilyHistory()
{
this.familyHistorySectionHeading.click();
}
/**
* Creates a new entry for family studies
*
* @param relative type of relative; one of "Child", "Parent", "Sibling"... etc.
* @param relative_id the reference if of the relative in the system
*/
public void newEntryFamilyStudy(String relative, String relative_id)
{
// click new family study button
this.newEntryFamilyStudy.click();
// select the type of relative
// this.waitUntilElementIsVisible(By.id("PhenoTips.RelativeClass_0_relative_type"));
new Select(this.thisPatientIsThe).selectByVisibleText(relative);
// input the id of the relative
this.ofPatientWithIdentifier.clear();
this.ofPatientWithIdentifier.sendKeys(relative_id);
}
/**
* Sets ethnicities in Family History tab
*
* @param maternal the maternal ethnicity of the patient
* @param paternal the paternal ethnicity of the patient
*/
public void setEthnicites(String maternal, String paternal)
{
this.maternalEthnicity.clear();
this.maternalEthnicity.sendKeys(maternal);
this.paternalEthnicity.clear();
this.paternalEthnicity.sendKeys(paternal);
}
/**
* Checkboxes global mode of inheritance for autosomal, polygenic and sporadic
*/
public void setGlobalModeOfInheritance()
{
this.globalInheritanceAutosomal.click();
this.globalInheritancePolygenic.click();
this.globalInheritanceSporadic.click();
}
/* PRENETAL AND PERINATAL HISTORY */
public void expandPrenatalAndPerinatalHistory()
{
this.prenatalAndPerinatalHistorySectionHeading.click();
}
/**
* Sets prenatal gestration at birth text box and checks the term birth box if wanted
*
* @param weeks the number of weeks to input in the text box
*/
public void setPrenatalGestationAtDelivery(String weeks)
{
this.gestationAtDelivery.clear();
this.gestationAtDelivery.sendKeys(weeks);
}
/**
* Sets the yes and no values for assisted reproduction boxes
*/
public void setAssistedReproduction()
{
this.assistedReproductionFertilityYes.click();
this.assistedReproductionInVitroNo.click();
}
/**
* Sets APGAR scores from the one and five minute options
*
* @param oneMinute a string that this one of the numbers "1" to "10" or "Unknown" for the one minute APGAR
* @param fiveMinute a string that this one of the numbers "1" to "10" or "Unknown" for the five minute APGAR
*/
public void setAPGARScores(String oneMinute, String fiveMinutes)
{
// this.waitUntilElementIsVisible(By.id("PhenoTips.PatientClass_0_apgar1"));
new Select(this.APGAROneMinute).selectByVisibleText(oneMinute);
// this.waitUntilElementDisappears(By.id("PhenoTips.PatientClass_0_apgar5"));
new Select(this.APGARFiveMinutes).selectByVisibleText(fiveMinutes);
}
public void setPrenatalNotes(String notes)
{
this.prenatalNotes.clear();
this.prenatalNotes.sendKeys(notes);
}
/**
* Sets the prenatal growth parameters
*
* @param other the text to goes in the other text box
*/
public void setPrenatalGrowthParameters(String other)
{
// doesn't work, element isn't visible
this.prenatalGrowthSmallGestationalYes.click();
this.prenatalGrowthLargeBirthYes.click();
this.prenatalGrowthOther.clear();
this.prenatalGrowthOther.sendKeys();
}
/**
* Sets the prenatal developement or birth information
*
* @param other the text that goes in the other text box
*/
public void setPrenatalDevelopmentOrBirth(String other)
{
// doesn't work, element isn't visible
this.prenatalDevelopmentPolyhydramniosNo.click();
this.prenatalDevelopmentOther.clear();
this.prenatalDevelopmentOther.sendKeys(other);
}
/**
* Enters text in the "medical and developmental history text box
*
* @param history the text to be entered
*/
public void setMedicalHistory(String history)
{
this.medicalHistory.clear();
this.medicalHistory.sendKeys(history);
}
/**
* Clicks the radio button "Late onset" in the radio group of "Global age at onset" buttons
*/
public void setLateOnset()
{
this.lateOnset.click();
}
/**
* Returns the number of elements that match the css for the "upload image" button
*
* @return the number of elements matching this css
*/
public int findElementsUploadImage()
{
return getDriver()
.findElements(
By.cssSelector("#PhenoTips\\2e PatientClass_0_reports_history_container > div.actions > span > a"))
.size();
}
public void clickTermBirth()
{
this.checkTermBirth.click();
}
public void openNewEntryListOfCandidateGenes()
{
this.newEntryListOfCandidateGenes.click();
}
public int checkGeneCandidateSearchHideSuggestions(String search)
{
this.geneCandidateSearch.clear();
this.geneCandidateSearch.sendKeys(search);
return getDriver()
.findElements(By.cssSelector("#body > div.suggestItems.ajaxsuggest > div:nth-child(1) > span")).size();
}
public void setGeneCandidateComment(String comment)
{
this.geneCandidateComment.clear();
this.geneCandidateComment.sendKeys(comment);
}
public void openNewEntryPreviouslyTested()
{
this.newEntryPreviouslyTested.click();
}
public int checkGenePreviouslySearchHideSuggestions(String search)
{
this.genePreviously.clear();
this.genePreviously.sendKeys(search);
return getDriver()
.findElements(By.cssSelector("#body > div.suggestItems.ajaxsuggest > div:nth-child(1) > span")).size();
}
public void setPreviouslyTestedGenesComment(String comment)
{
this.genePreviouslyTestedComment.clear();
this.genePreviouslyTestedComment.sendKeys(comment);
}
public void expandCaseResolution()
{
this.caseResolutionSectionHeading.click();
}
public void setCaseSolved()
{
this.caseSolved.click();
}
public void setIDsAndNotes(String pID, String gID, String notes)
{
this.pubmedID.clear();
this.pubmedID.sendKeys(pID);
this.geneID.clear();
this.geneID.sendKeys(gID);
this.resolutionNotes.clear();
this.resolutionNotes.sendKeys(notes);
}
public void setPatientIdentifier(String value)
{
this.patientIdentifier.clear();
this.patientIdentifier.sendKeys(value);
}
public void familyHealthConditions(String value)
{
this.familyHealthConditions.clear();
this.familyHealthConditions.sendKeys(value);
}
public void expandMedicalHistory()
{
this.medicalHistorySectionHeading.click();
}
public void expandMeasurements()
{
this.measurementsSectionHeading.click();
}
public void createNewMeasurementsEntry()
{
this.newEntryMeasurements.click();
}
/* setting measurements */
public void setMeasurementWeight(String value)
{
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.MeasurementsClass_0_weight"));
this.measurementWeight.clear();
this.measurementWeight.click();
this.measurementWeight.sendKeys(value);
}
public void setMeasurementHeight(String value)
{
this.measurementHeight.clear();
this.measurementHeight.click();
this.measurementHeight.sendKeys(value);
}
public void setMeasurementArmSpan(String value)
{
this.measurementArmSpan.clear();
this.measurementArmSpan.click();
this.measurementArmSpan.sendKeys(value);
}
public void setMeasurementSittingHeight(String value)
{
this.measurementSittingHeight.clear();
this.measurementSittingHeight.click();
this.measurementSittingHeight.sendKeys(value);
}
public void setMeasurementHeadCircumference(String value)
{
this.measurementHeadCircumference.clear();
this.measurementHeadCircumference.sendKeys(value);
}
public void setMeasurementPhiltrumLength(String value)
{
this.measurementPhiltrumLength.clear();
this.measurementPhiltrumLength.sendKeys(value);
}
public void setMeasurementLeftEarLength(String value)
{
this.measurementLeftEarLength.clear();
this.measurementLeftEarLength.sendKeys(value);
}
public void setMeasurementRightEarLength(String value)
{
this.measurementRightEarLength.clear();
this.measurementRightEarLength.sendKeys(value);
}
public void setMeasurementOuterCanthalDistance(String value)
{
this.measurementOuterCanthalDistance.clear();
this.measurementOuterCanthalDistance.sendKeys(value);
}
public void setMeasurementInnerCanthalDistance(String value)
{
this.measurementInnerCanthalDistance.clear();
this.measurementInnerCanthalDistance.sendKeys(value);
}
public void setMeasuremtnePalpebralFissureLength(String value)
{
this.measurementPalpebralFissureLength.clear();
this.measurementPalpebralFissureLength.sendKeys(value);
}
public void setMeasurementInterpupilaryDistance(String value)
{
this.measurementInterpupilaryDistance.clear();
this.measurementInterpupilaryDistance.sendKeys(value);
}
public void setMeasurementLeftHandLength(String value)
{
this.measurementLeftHandLength.clear();
this.measurementLeftHandLength.sendKeys(value);
}
public void setMeasurementLeftPalmLength(String value)
{
this.measurementLeftPalmLength.clear();
this.measurementLeftPalmLength.sendKeys(value);
}
public void setMeasurementLeftFootLength(String value)
{
this.measurementLeftFootLength.clear();
this.measurementLeftFootLength.sendKeys(value);
}
public void setMeasurementRightHandLength(String value)
{
this.measurementRightHandLength.clear();
this.measurementRightHandLength.sendKeys(value);
}
public void setMeasurementRightPalmLength(String value)
{
this.measurementRightPalmLength.clear();
this.measurementRightPalmLength.sendKeys(value);
}
public void setMeasurementRightFootLength(String value)
{
this.measurementRightFootLength.clear();
this.measurementRightFootLength.sendKeys(value);
}
public boolean checkIfGrowthChartsAreShowing()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public String checkIfGrowthChartsAreShowingByText()
{
return this.checkIfGrowthChartsAreShowingByText.getText();
}
public void expandGenotypeInformation()
{
this.genotypeInformationSectionHeading.click();
}
///////////////////////////////////
// public void setGenotypeInformationComments(String value)
// {
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.InvestigationClass_0_comments"));
// this.genotypeInformationComments.clear();
// this.genotypeInformationComments.sendKeys(value);
// }
// public void setGenotypeInformationGene(String value)
// {
// this.genotypeInformationGene.clear();
// this.genotypeInformationGene.sendKeys(value);
// }
public void setPatientClinicallyNormal()
{
this.patientIsClinicallyNormal.click();
}
public void expandClinicalSymptomsAndPhysicalFindings()
{
this.clinicalSymptomsAndPhysicalFindings.click();
}
public boolean checkIfClinicalSymptomsAndPhysicalFindingsExpanded(By by)
{
try {
getDriver().findElement(By.id("PhenoTips.PatientClass_0_unaffected"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void selectPhenotype(String id, boolean positive)
{
BaseElement
.getUtil()
.findElementWithoutWaiting(
getDriver(),
By.cssSelector("label[for='PhenoTips.PatientClass_0_" + (positive ? "" : "negative_") + "phenotype_"
+ id + "']")).click();
;
}
public void setHypotelorismYes()
{
selectPhenotype("HP:0000601", true);
}
public void setStature3rdPercentile()
{
selectPhenotype("HP:0004322", true);
}
public void setWeight3rdPercentile()
{
selectPhenotype("HP:0004325", true);
}
public void setHeadCircumference3rdPercentile()
{
selectPhenotype("HP:0000252", true);
}
public void setHemihypertrophyYes()
{
selectPhenotype("HP:0001528", true);
}
public void setCraniosynostosisYes()
{
selectPhenotype("HP:0001363", true);
}
public void setCleftUpperLipNO()
{
selectPhenotype("HP:0000204", false);
}
public void setCleftPalateYes()
{
selectPhenotype("HP:0000175", true);
}
public void setAbnormalFacialShapeYes()
{
selectPhenotype("HP:0001999", true);
}
public void setVisualImpairmentYes()
{
selectPhenotype("HP:0000505", true);
}
public void setAbnormalityOfTheCorneaNO()
{
selectPhenotype("HP:0000481", false);
}
public void setColobomaNO()
{
selectPhenotype("HP:0000589", false);
}
public void setSensorineuralNO()
{
selectPhenotype("HP:0000407", false);
}
public void setAbnormalityOfTheInnerEarYes()
{
selectPhenotype("HP:0000359", true);
}
public void setHyperpigmentationOfTheSkinYes()
{
selectPhenotype("HP:0000953", true);
}
public void setCapillaryHemangiomasNO()
{
selectPhenotype("HP:0005306", false);
}
public void setVentricularSeptalDefectNO()
{
selectPhenotype("HP:0001629", false);
}
public void setArrhythmiaYes()
{
selectPhenotype("HP:0011675", true);
}
public void setCongenitalDiaphragmaticHerniaYes()
{
selectPhenotype("HP:0000776", true);
}
public void setAbnormalityOfTheLungNO()
{
selectPhenotype("HP:0002088", false);
}
public void setLowerLimbUndergrowthYes()
{
selectPhenotype("HP:0009816", true);
}
public void setScoliosisYes()
{
selectPhenotype("HP:0002650", true);
}
public void setAbnormalityOfTheVertebralColumnNO()
{
selectPhenotype("HP:0000925", false);
}
public void setCholestasisYes()
{
selectPhenotype("HP:0001396", true);
}
public void setDiabetesMellitusNO()
{
selectPhenotype("HP:0000819", false);
}
public void setHorseshoeKidneyNO()
{
selectPhenotype("HP:0000085", false);
}
public void setHypospadiasYes()
{
selectPhenotype("HP:0000047", true);
}
public void setDelayedFineMotorDevelopmentYes()
{
selectPhenotype("HP:0010862", true);
}
public void setAttentionDeficitHyperactivityDisorderNO()
{
selectPhenotype("HP:0007018", false);
}
public void setAustismYes()
{
selectPhenotype("HP:0000717", true);
}
public void setSeizuresYes()
{
selectPhenotype("HP:0001250", true);
}
public void setSpinalDysraphismNO()
{
selectPhenotype("HP:0010301", false);
}
public void coarctationOfAortaDropDown()
{
this.coarctationOfAortaDropDown.click();
}
public String checkCoarctationOfAortaDropDown()
{
return this.checkCoarctationOfAortaDropDown.getText();
}
public void hemihypertrophyAddDetails()
{
this.hemihypertrophyAddDetails.click();
}
public void ageOfOnsetHemihypertrophy()
{
this.ageOfOnsetHemihypertrophy.click();
}
public void setNeonatalOnsetHemihypertrophy()
{
this.neonatalOnsetHemihypertrophy.click();
}
public void temporalPatternHemihypertrophy()
{
this.temporalPatternHemihypertrophy.click();
}
public void setSubacuteTemporalPatternHemihypertrophy()
{
this.subacuteTemporalPatternHemihypertrophy.click();
}
public void deleteCleftPalate()
{
this.deleteCleftPalate.click();
}
public void abnormalFacialShapeAddDetails()
{
this.abnormalFacialShapeAddDetails.click();
}
public void paceOfProgressionAbnormalFacialShape()
{
this.paceOfProgressionAbnormalFacialShape.click();
}
public void slowPaceOfProgressionAbnormalFacialShape()
{
this.slowPaceOfProgressionAbnormalFacialShape.click();
}
public void hypotelorismAddDetails()
{
this.hypotelorismAddDetails.click();
}
public void severityHypotelorism()
{
this.severityHypotelorism.click();
}
public void moderateSeverityHypotelorism()
{
this.moderateSeverityHypotelorism.click();
}
public void abnormalityOfTheInnerEarAddDetails()
{
this.abnormalityOfTheInnerEarAddDetails.click();
}
public void spatialPatternAbnormalityOfTheInnerEar()
{
this.spatialPatternAbnormalityOfTheInnerEar.click();
}
public void distalSpatialPatternAbnomalityOfTheInnerEar()
{
this.distalSpatialPatternAbnormalityOfTheInnerEar.click();
}
public void arrythmiaAddDetails()
{
this.arrhythmiaAddDetails.click();
}
public void arrythmiaComments(String value)
{
this.arrhythmiaComments.clear();
this.arrhythmiaComments.sendKeys(value);
}
public void scoliosisAddDetails()
{
this.scoliosisAddDetails.click();
}
public void lateralityScoliosis()
{
this.lateralityScoliosis.click();
}
public void rightLateralityScoliosis()
{
this.rightLateralityScoliosis.click();
}
public void seizuresAddDetails()
{
this.seizuresAddDetails.click();
}
public void severitySeizures()
{
this.severitySeizures.click();
}
public void mildSeveritySeizures()
{
this.mildSeveritySeizures.click();
}
public void asymmetryOfTheEarsYes()
{
this.asymmetryOfTheEarsYes.click();
}
public void immunodeficiencyYes()
{
this.immunodeficiencyYes.click();
}
public void abnormalityOfTheCartoidArteriesYes()
{
this.abnormalityOfTheCartoidArteriesYes.click();
}
public void bifidTongueYes()
{
this.bifidTongueYes.click();
}
public void bifidRibsYes()
{
this.bifidRibsYes.click();
}
public void hypsarrhythmiaNO()
{
this.hypsarrhythmiaNO.click();
}
public void phenotypeQuickSearch(String value)
{
this.phenotypeQuickSearch.clear();
this.phenotypeQuickSearch.sendKeys(value);
}
public void quickSearchCataractYes()
{
this.quickSearchCataractYes.click();
}
public void expandDiagnosis()
{
this.diagnosisSectionHeading.click();
}
public void setDiagnosisAdditionalComments(String value)
{
this.diagnosisAdditionalComments.clear();
this.diagnosisAdditionalComments.sendKeys(value);
}
public void setSmithLemliOptizSyndrome()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__270400"));
this.smithLemliOptizSyndrome.click();
}
public void setWatsonSyndrome()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__193520"));
this.watsonSyndrome.click();
}
public void setIndicationForReferral(String value)
{
this.indicationForReferral.clear();
this.indicationForReferral.sendKeys(value);
}
public void setPrenatalGrowthPatternsOther(String value)
{
this.prenatalGrowthPatternsOther.clear();
this.prenatalGrowthPatternsOther.sendKeys(value);
}
public void setPositvieFerricChlorideTestYes()
{
this.positiveFerricChlorideTestYes.click();
}
public void setPrenatalDevelopmentOrBirthOther(String value)
{
this.prenatalDevelopmentOrBirthOther.clear();
this.prenatalDevelopmentOrBirthOther.sendKeys(value);
}
public void setDysplasticTestesYes()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0008733']]"));
this.dysplasticTestesYes.click();
}
public String getWeightPctl()
{
return this.weightPctl.getText();
}
public String getHeightPctl()
{
return this.heightPctl.getText();
}
public String getBMIPctl()
{
return this.bmiPctl.getText();
}
public String getSittingPctl()
{
return this.sittingPctl.getText();
}
public String getHeadCircumferencePctl()
{
return this.headCircumferencePctl.getText();
}
public String getPhiltrumPctl()
{
return this.philtrumPctl.getText();
}
public String getLeftEarPctl()
{
return this.leftEarPctl.getText();
}
public String getRightEarPctl()
{
return this.rightEarPctl.getText();
}
public String getOuterCanthalPctl()
{
return this.outerCanthalPctl.getText();
}
public String getInnerCanthalPctl()
{
return this.innerCanthalPctl.getText();
}
public String getPalpebralFissurePctl()
{
return this.palpebralFissurePctl.getText();
}
public String getInterpupilaryPctl()
{
return this.interpupilaryPctl.getText();
}
public String getLeftPalmPctl()
{
return this.leftPalmPctl.getText();
}
public String getLeftFootPctl()
{
return this.leftFootPctl.getText();
}
public String getRightPalmPctl()
{
return this.rightPalmPctl.getText();
}
public String getRightFootPctl()
{
return this.rightFootPctl.getText();
}
public String getBMINumber()
{
return this.bmiNumber.getText();
}
public void setOMIMDisorder(String value)
{
this.OMIMDisorderBar.clear();
this.OMIMDisorderBar.sendKeys(value);
}
public void setOMIMDisorderWolfSyndrome()
{
this.OMIMDisorderWolfSyndrome.click();
}
public void excludeLowerLimbUndergrowth()
{
this.OMIMBoxLowerLimbUnderGrowth.click();
}
public String checkLowerLimbUndergrowthExcluded()
{
return this.OMIMBoxLowerLimbUnderGrowthExcluded.getText();
}
public String checkSmithLemliInOMIM()
{
return this.checkSmithLemliInOMIM.getText();
}
public void setCriDuChatSyndromeFromBottom()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__123450"));
this.criDuChatSyndrome.click();
}
public String checkCriDuChatAppears()
{
return this.checkCriDuChatAppears.getText();
}
public boolean checkCriDuChatDisappearsFromTop(By by)
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'fieldset omim_id']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][@value = '123450']//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStatureLightningBoltAppearsOnRight()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-item'][.//input[@value = 'HP:0004322']]//*[contains(@class, 'fa-bolt')]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkHypotelorismLightningBoltAppearsOnRight()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[contains(@class, 'fa-bolt')]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkCriDuChatDisappearsFromBottom()
{
getDriver()
.findElement(
By.xpath(
"//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][@value = '123450']//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']"))
.isSelected();
return true;
}
public void setCriDuChatFromTop()
{
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.PatientClass_0_omim_id_123450"));
this.criDuChatOMIMTop.click();
}
public void setPreauricularPitYes()
{
selectPhenotype("HP:0004467", true);
}
public boolean checkPreauricularPitAppearsOnRight()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0004467']]//*[@class =
// 'yes'][text() = 'Preauricular pit']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0004467']]//*[@class = 'yes'][text() = 'Preauricular pit']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void setNystagmusNO()
{
selectPhenotype("HP:0000639", false);
}
public boolean checkNystagmusAppearsOnRightNO()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'summary-item'][//label[@class = 'no']][//input[@value = 'HP:0000639']]//*[@class =
// 'no'][text() = 'Nystagmus']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'no']][//input[@value = 'HP:0000639']]//*[@class = 'no'][text() = 'Nystagmus']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkNystagmusReturnsToNA()
{
try {
return getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'term-entry')][.//*[@value = 'HP:0000639']]//label[contains(@class, 'na')]"))
.getAttribute("class").contains("selected");
} catch (NoSuchElementException e) {
return false;
}
}
public void deleteNystagmusFromRight()
{
this.deleteNystagmusRight.click();
}
public boolean checkPolyphagiaDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@class = 'background-search']//*[@class = 'phenotype'][//label[@class = 'yes']][//input[@value = 'HP:0002591']]//*[@class = 'initialized']//*[@class = 'yes-no-picker-label'][text() = 'polyphagia']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'background-search']//*[@class = 'phenotype'][//label[@class = 'yes']][//input[@value = 'HP:0002591']]//*[@class = 'initialized']//*[@class = 'yes-no-picker-label'][text() = 'polyphagia']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkImmunodeficiencyDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkAbnormalityOfTheCartoidArteriesDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkBifidTongueDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010297']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010297']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public void polyphagiaYes()
{
this.polyphagiaYes.click();
}
public void browseRelatedTermsCataract()
{
this.getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'suggestItems')]//*[contains(@class, 'suggestItem')][//*[text() = 'Cataract']]//*[contains(@class, 'xHelpButton')]"))
.click();
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'resultContainer']//li[contains(@class, 'xitem')]//*[contains(@class, 'xTooltip')]//*[contains(text(), 'Browse related terms')]"));
this.browseRelatedTermsCataract.click();
}
public void abnormalityOfTheLensGoUP()
{
this.abnormalityOfTheLensGoUp.click();
}
public String abnormalityOfTheAnteriorSegmentOfTheEye()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'ontology-tree']//*[@class = 'entry parent']//*[@class = 'value'][text() = 'Abnormality of the anterior segment of the eye']"));
return this.abnormalityOfTheAnteriorSegmentOfTheEyeCheck.getText();
}
public void phacodonesisYes()
{
this.phacodonesisYes.click();
}
public void closeBrowseRelatedTerms()
{
this.closeBrowseRelatedTerms.click();
}
public void hideQuickSearchBarSuggestions()
{
this.hideQuickSearchBarSuggestions.click();
}
public boolean checkPhacodonesisAppearsOnRight()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0012629']]//*[@class = 'yes'][text() = 'Phacodonesis']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0012629']]//*[@class = 'yes'][text() = 'Phacodonesis']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void openDateOfMeasurements()
{
this.dateOfMeasurments.click();
}
public void setDate1()
{
this.date1.click();
}
public void setDate12()
{
this.date12.click();
}
public void setGastroschisisYes()
{
selectPhenotype("HP:0001543", true);
}
public boolean checkSmithLemliSyndrome()
{
this.getDriver().waitUntilElementIsVisible(By.id("result__270400"));
try {
getDriver().findElement(By.id("result__270400"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void moreInfoHypotelorism()
{
this.moreInfoHypotelorism.click();
}
public String checkMoreInfoOpened()
{
return this.checkMoreInfoHypotelorismOpened.getText();
}
public void closeMoreInfoHypotelorism()
{
this.closeMoreInfoHypotelorism.click();
}
public void moreInfoSex()
{
this.moreInfoSex.click();
}
public String checkMoreInfoSex()
{
return this.checkMoreInfoSex.getText();
}
public void closeMoreInfoSex()
{
this.closeMoreInfoSex.click();
}
public void moreInfoIndicationForReferral()
{
this.moreInfoIndicationForReferral.click();
}
public String checkMoreInfoIndicationForReferral()
{
return this.checkMoreInfoIndicationForReferral.getText();
}
public void closeMoreInfoIndicationForReferral()
{
this.closeMoreInfoIndicationForReferral.click();
}
public void moreInfoNewEntryFamilyStudy()
{
this.moreInfoNewEntryFamilyStudy.click();
}
public String checkMoreInfoFamilyStudy()
{
return this.checkMoreInfoNewEntryFamilyStudy.getText();
}
public void closeMoreInfoNewEntryFamilyStudy()
{
this.closeMoreInfoNewEntryFamilyStudy.click();
}
public void setPatientIsTheRelativeOf(String relative)
{
this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.RelativeClass_0_relative_type"));
new Select(this.thisPatientIsThe).selectByVisibleText(relative);
}
public void relativeOfCurrentPatient(String value)
{
this.ofPatientWithIdentifier.clear();
this.ofPatientWithIdentifier.sendKeys(value);
}
public void moreInfoFamilyHealthConditions()
{
this.moreInfoFamilyHealthConditions.click();
}
public String checkMoreInfoFamilyHealthConditions()
{
return this.checkMoreInfoFamilyHealthConditions.getText();
}
public void closeMoreInfoFamilyHealthConditions()
{
this.closeMoreInfoFamilyHealthConditions.click();
}
public void moreInfoGestation()
{
this.moreInfoGestation.click();
}
public String checkMoreInfoGestation()
{
return this.checkMoreInfoGestation.getText();
}
public void closeMoreInfoGestation()
{
this.closeMoreInfoGestation.click();
}
public void moreInfoGlobalAgeOfOnset()
{
this.moreInfoGlobalAgeOfOnset.click();
}
public String checkMoreInfoGlobalAgeOfOnset()
{
return this.checkMoreInfoGlobalAgeOfOnset.getText();
}
public void closeMoreInfoGlobalAgeOfOnset()
{
this.closeMoreInfoGlobalAgeOfOnset.click();
}
public void moreInfoNewEntryMeasurements()
{
this.moreInfoNewEntryMeasurements.click();
}
public String checkMoreInfoNewEntryMeasurements()
{
return this.checkMoreInfoNewEntryMeasurements.getText();
}
public void closeMoreInfoNewEntryMeasurements()
{
this.closeMoreInfoNewEntryMeasurements.click();
}
public void moreInfoOMIMDisorder()
{
this.moreInfoOMIMDisorder.click();
}
public String checkMoreInfoOMIMDisorder()
{
return this.checkMoreInfoOMIMDisorder.getText();
}
public void closeMoreInfoOMIMDisorder()
{
this.closeMoreInfoOMIMDisorder.click();
}
public void hideYouMayWantToInvestigate()
{
this.youMayWantToInvestigate.click();
}
public boolean checkYouMayWantToInvestigateHid()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@class = 'background-suggestions]//*[@class = 'phenotype'][@class = 'yes'][//input[@value = 'HP:0000878']]//*[@class = 'yes-no-picker']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'background-suggestions]//*[@class = 'phenotype'][@class = 'yes'][//input[@value = 'HP:0000878']]//*[@class = 'yes-no-picker']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void moreInfoSelectObservedPhenotypes()
{
this.moreInfoSelectObservedPhenotypes.click();
}
public String checkMoreInfoSelectObservedPhenotypes()
{
return this.checkMoreInfoSelectObservedPhenotypes.getText();
}
public void closeMoreInfoSelectObservedPhenotypes()
{
this.closeMoreInfoSelectObservedPhenotypes.click();
}
public void collapseAllPhenotypes()
{
this.collapseAllPhenotypes.click();
}
public boolean checkAllPhenotypesCollapsed()
{
this.getDriver().waitUntilElementDisappears(
By.cssSelector("label[for='PhenoTips.PatientClass_0_phenotype_HP:0001363]"));
try {
getDriver().findElement(By.cssSelector("label[for='PhenoTips.PatientClass_0_phenotype_HP:0001363]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void expandAllPhenotypes()
{
this.expandAllPhenotypes.click();
}
public void setYearDateOfBirth(String year)
{
new Select(this.setYearDateOfBirth).selectByVisibleText(year);
}
public void setYearMeasurement(String year)
{
new Select(this.setYearDateOfBirth).selectByVisibleText(year);
}
public void setMonthDateOfBirth(String month)
{
new Select(this.setMonthDate).selectByVisibleText(month);
}
public void setMonthMeasurement(String month)
{
new Select(this.setMonthDate).selectByVisibleText(month);
}
public boolean checkDecreasedBodyWeight()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkDecreasedBodyWeightDisappears()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStature()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStatureDisappears()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public String checkChartTitleChangesMale()
{
return this.chartTitleBoys.getText();
}
public String checkChartTitleChangesFemale()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, girls']"));
return this.chartTitleGirls.getText();
}
public String checkChartTitleChangesOlderMale()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath("//*[@class = 'chart-title'][text() = 'Weight for age, 2 to 20 years, boys']"));
return this.chartTitleOlderBoys.getText();
}
@Override
public PatientRecordViewPage clickSaveAndView()
{
this.saveAndViewButton.click();
return new PatientRecordViewPage();
}
@Override
public void clickSaveAndContinue()
{
this.saveAndContinueButton.click();
}
public String getAgeMeasurements()
{
return this.getAgeMeasurements.getText();
}
@SuppressWarnings("unchecked")
@Override
protected PatientRecordViewPage createViewPage()
{
return new PatientRecordViewPage();
}
@Override
public void waitUntilPageJSIsLoaded()
{
getDriver().waitUntilJavascriptCondition("return window.Prototype != null && window.Prototype.Version != null");
}
}
| components/patient-data/pageobjects/src/main/java/org/phenotips/data/test/po/PatientRecordEditPage.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
*/
package org.phenotips.data.test.po;
import org.xwiki.test.ui.po.BaseElement;
import org.xwiki.test.ui.po.InlinePage;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
/**
* Represents the actions possible on a patient record in view mode.
*
* @version $Id$
* @since 1.0RC1
*/
public class PatientRecordEditPage extends InlinePage
{
@FindBy(css = "#document-title h1")
private WebElement recordId;
@FindBy(id = "HFamilyhistoryandpedigree")
WebElement familyHistorySectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_maternal_ethnicity_2")
WebElement maternalEthnicity;
@FindBy(id = "PhenoTips.PatientClass_0_paternal_ethnicity_2")
WebElement paternalEthnicity;
@FindBy(id = "HPrenatalandperinatalhistory")
WebElement prenatalAndPerinatalHistorySectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_family_history")
WebElement familyHealthConditions;
@FindBy(css = ".fieldset.gestation input[type=\"text\"]")
WebElement gestationAtDelivery;
@FindBy(id = "HMedicalhistory")
WebElement medicalHistorySectionHeading;
@FindBy(id = "HMeasurements")
WebElement measurementsSectionHeading;
@FindBy(css = ".measurement-info.chapter .list-actions a.add-data-button")
WebElement newEntryMeasurements;
/* MEASUREMENT ELEMENTS */
@FindBy(id = "PhenoTips.MeasurementsClass_0_weight")
WebElement measurementWeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_height")
WebElement measurementHeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_armspan")
WebElement measurementArmSpan;
@FindBy(id = "PhenoTips.MeasurementsClass_0_sitting")
WebElement measurementSittingHeight;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hc")
WebElement measurementHeadCircumference;
@FindBy(id = "PhenoTips.MeasurementsClass_0_philtrum")
WebElement measurementPhiltrumLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ear")
WebElement measurementLeftEarLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ear_right")
WebElement measurementRightEarLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ocd")
WebElement measurementOuterCanthalDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_icd")
WebElement measurementInnerCanthalDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_pfl")
WebElement measurementPalpebralFissureLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_ipd")
WebElement measurementInterpupilaryDistance;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hand")
WebElement measurementLeftHandLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_palm")
WebElement measurementLeftPalmLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_foot")
WebElement measurementLeftFootLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_hand_right")
WebElement measurementRightHandLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_palm_right")
WebElement measurementRightPalmLength;
@FindBy(id = "PhenoTips.MeasurementsClass_0_foot_right")
WebElement measurementRightFootLength;
@FindBy(id = "HGenotypeinformation")
WebElement genotypeInformationSectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_unaffected")
WebElement patientIsClinicallyNormal;
@FindBy(id = "HDiagnosis")
WebElement diagnosisSectionHeading;
//
@FindBy(id = "PhenoTips.PatientClass_0_diagnosis_notes")
WebElement diagnosisAdditionalComments;
@FindBy(id = "result__270400")
WebElement smithLemliOptizSyndrome;
@FindBy(id = "result__193520")
WebElement watsonSyndrome;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[@class = 'tool'][text() = 'Add details']")
WebElement hemihypertrophyAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[contains(@class, 'age_of_onset')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement ageOfOnsetHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//dd[@class = 'age_of_onset']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0003623']]//*[@value = 'HP:0003623']")
WebElement neonatalOnsetHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//*[contains(@class, 'temporal_pattern')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement temporalPatternHemihypertrophy;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001528']]//dd[@class = 'temporal_pattern']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0011011']]//*[@value = 'HP:0011011']")
WebElement subacuteTemporalPatternHemihypertrophy;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000175']]//*[@class = 'tool'][text() = 'Delete']")
WebElement deleteCleftPalate;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001999']]//*[@class = 'tool'][text() = 'Add details']")
WebElement abnormalFacialShapeAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0001999']]//*[contains(@class, 'pace_of_progression')]//*[contains(@class, 'collapse-button')][text() = '►']")
WebElement paceOfProgressionAbnormalFacialShape;
@FindBy(id = "PhenoTips.PhenotypeMetaClass_1_pace_of_progression_HP:0003677")
WebElement slowPaceOfProgressionAbnormalFacialShape;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[@class = 'tool'][text() = 'Add details']")
WebElement hypotelorismAddDetails;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[contains(@class, 'severity')]//*[@class = 'collapse-button'][text() = '►']")
WebElement severityHypotelorism;
@FindBy(xpath = "//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//dd[@class = 'severity']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012826']]//*[@value = 'HP:0012826']")
WebElement moderateSeverityHypotelorism;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000359']]//*[@class = 'tool'][text() = 'Add details']")
WebElement abnormalityOfTheInnerEarAddDetails;
@FindBy(xpath = "//*[@class = 'group-contents'][.//input[@value = 'HP:0000359']]//*[contains(@class, 'spatial_pattern')]//*[@class = 'collapse-button'][text() = '►']")
WebElement spatialPatternAbnormalityOfTheInnerEar;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000359']]//dd[@class = 'spatial_pattern']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012839']]//*[@value = 'HP:0012839']")
WebElement distalSpatialPatternAbnormalityOfTheInnerEar;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0011675']]//*[@class = 'tool'][text() = 'Add details']")
WebElement arrhythmiaAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0011675']]//dd[@class = 'comments']//textarea[contains(@name, 'PhenoTips.PhenotypeMetaClass')]")
WebElement arrhythmiaComments;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//*[@class = 'tool'][text() = 'Add details']")
WebElement scoliosisAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//*[contains(@class, 'laterality')]//*[@class = 'collapse-button'][text() = '►']")
WebElement lateralityScoliosis;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0002650']]//dd[@class = 'laterality']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012834']]//*[@value = 'HP:0012834']")
WebElement rightLateralityScoliosis;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//*[@class = 'tool'][text() = 'Add details']")
WebElement seizuresAddDetails;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//*[contains(@class, 'severity')]//*[@class = 'collapse-button'][text() = '►']")
WebElement severitySeizures;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0001250']]//dd[@class = 'severity']//li[contains(@class, 'term-entry')][.//input[@value = 'HP:0012825']]//*[@value = 'HP:0012825']")
WebElement mildSeveritySeizures;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010722']]")
WebElement asymmetryOfTheEarsYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]")
WebElement immunodeficiencyYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]")
WebElement abnormalityOfTheCartoidArteriesYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//label[@class = 'yes'][.//input[@value = 'HP:0010297']]")
WebElement bifidTongueYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'yes')][.//input[@value = 'HP:0002591']]")
WebElement polyphagiaYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'yes')][.//input[@value = 'HP:0000892']]")
WebElement bifidRibsYes;
@FindBy(xpath = "//*[contains(@class, 'background-search')]//*[contains(@class, 'no')][.//input[@value = 'HP:0002521']]")
WebElement hypsarrhythmiaNO;
@FindBy(xpath = "//*[contains(@class, 'term-entry')][.//label[text() = 'Coarctation of aorta']]/span[@class = 'expand-tool']")
WebElement coarctationOfAortaDropDown;
@FindBy(xpath = "//*[contains(@class, 'entry')]//*[contains(@class, 'info')][.//*[text() = 'Coarctation of abdominal aorta']]//*[@class = 'value']")
WebElement checkCoarctationOfAortaDropDown;
@FindBy(id = "quick-phenotype-search")
WebElement phenotypeQuickSearch;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0000518']]")
WebElement quickSearchCataractYes;
@FindBy(id = "PhenoTips.PatientClass_0_indication_for_referral")
WebElement indicationForReferral;
@FindBy(xpath = "//*[@class = 'prenatal_phenotype-other custom-entries'][//*[contains(@class, 'suggested')]]//*[contains(@class, 'suggested')]")
WebElement prenatalGrowthPatternsOther;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0003612']]")
WebElement positiveFerricChlorideTestYes;
@FindBy(xpath = "//*[@class = 'prenatal_phenotype-group'][.//*[@id = 'HPrenatal-development-or-birth']]//*[contains(@class, 'prenatal_phenotype-other')][//*[contains(@class, 'suggested')]]//*[contains(@class, 'suggested')]")
WebElement prenatalDevelopmentOrBirthOther;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'yes'][.//input[@value = 'HP:0008733']]")
WebElement dysplasticTestesYes;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'weight_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement weightPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'height_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement heightPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'bmi_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement bmiPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'sitting_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement sittingPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'hc_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement headCircumferencePctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'philtrum_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement philtrumPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ear_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftEarPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ear_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightEarPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ocd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement outerCanthalPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'icd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement innerCanthalPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'pfl_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement palpebralFissurePctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'ipd_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement interpupilaryPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'palm_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftPalmPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'foot_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement leftFootPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'palm_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightPalmPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'foot_right_evaluation']//*[contains(@class, 'displayed-value')]")
WebElement rightFootPctl;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'bmi']//*[contains(@class, 'displayed-value')]")
WebElement bmiNumber;
@FindBy(id = "PhenoTips.PatientClass_0_omim_id")
WebElement OMIMDisorderBar;
@FindBy(xpath = "//*[@class = 'resultContainer']//*[@class = 'suggestValue'][text() = '#194190 WOLF-HIRSCHHORN SYNDROME']")
WebElement OMIMDisorderWolfSyndrome;
@FindBy(xpath = "//*[@class = 'ncbi-search-box']//*[@id = 'defaultSearchTerms']//*[@class = 'search-term symptom'][text() = 'Lower limb undergrowth']")
WebElement OMIMBoxLowerLimbUnderGrowth;
@FindBy(xpath = "//*[@class = 'ncbi-search-box']//*[@id = 'defaultSearchTerms']//*[@class = 'search-term symptom disabled'][text() = 'Lower limb undergrowth']")
WebElement OMIMBoxLowerLimbUnderGrowthExcluded;
@FindBy(xpath = "//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][.//input[@value = '270400']]//*[@class = 'value'][text()='#270400 SMITH-LEMLI-OPITZ SYNDROME']")
WebElement checkSmithLemliInOMIM;
@FindBy(id = "result__123450")
WebElement criDuChatSyndrome;
@FindBy(xpath = "//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][.//input[@value = '123450']]//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']")
WebElement checkCriDuChatAppears;
@FindBy(id = "PhenoTips.PatientClass_0_omim_id_123450")
WebElement criDuChatOMIMTop;
@FindBy(xpath = "//*[contains(@class, 'summary-item')][.//input[@value = 'HP:0000639']]//*[@class = 'tool'][text() = 'Delete']")
WebElement deleteNystagmusRight;
@FindBy(xpath = "//*[@class = 'resultContainer']//li[contains(@class, 'xitem')]//*[contains(@class, 'xTooltip')]//*[contains(text(), 'Browse related terms')]")
WebElement browseRelatedTermsCataract;
@FindBy(xpath = "//*[@class = 'entry-data'][.//*[contains(@class, 'yes-no-picker')]][.//*[@value = 'HP:0000517']]//*[@class = 'value'][text() = 'Abnormality of the lens']")
WebElement abnormalityOfTheLensGoUp;
@FindBy(xpath = "//*[@class = 'entry-data'][.//*[contains(@class, 'yes-no-picker')]][.//*[@value = 'HP:0004328']]//*[@class = 'value'][text() = 'Abnormality of the anterior segment of the eye']")
WebElement abnormalityOfTheAnteriorSegmentOfTheEyeCheck;
@FindBy(xpath = "//*[contains(@class, 'msdialog-modal-container')]//*[@class = 'msdialog-box']//*[@class = 'msdialog-close']")
WebElement closeBrowseRelatedTerms;
@FindBy(xpath = "//*[contains(@class, 'entry descendent')][.//span[contains(@class, 'yes-no-picker')]][.//label[@class = 'yes']][.//input[@value = 'HP:0012629']]//*[contains(@class, 'yes-no-picker')]//*[@class = 'yes']")
WebElement phacodonesisYes;
@FindBy(xpath = "//*[contains(@class, 'suggestItems')]//*[@class = 'hide-button-wrapper']//*[@class = 'hide-button']")
WebElement hideQuickSearchBarSuggestions;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[@class = 'month']")
WebElement setMonthDate;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[contains(@class, 'cds_body')]//td[.//div[text() = '1']][1]")
WebElement date1;
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[contains(@class, 'cds_body')]//td[.//div[text() = '12']][1]")
WebElement date12;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[contains(@class, 'phenotype-info')]")
WebElement moreInfoHypotelorism;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[@class = 'xTooltip']//*[@class = 'value']")
WebElement checkMoreInfoHypotelorismOpened;
@FindBy(xpath = "//*[@class = 'term-entry'][.//*[@value = 'HP:0000601']]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoHypotelorism;
@FindBy(xpath = "//*[@class = 'fieldset gender gender']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoSex;
@FindBy(xpath = "//*[contains(@class, 'patient-info')]//*[contains(@class, 'gender')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoSex;
@FindBy(xpath = "//*[contains(@class, 'patient-info')]//*[contains(@class, 'gender')]//*[@class = 'xTooltip']//span[@class = 'hide-tool']")
WebElement closeMoreInfoSex;
@FindBy(css = ".indication_for_referral .xHelpButton")
WebElement moreInfoIndicationForReferral;
@FindBy(css = ".indication_for_referral .xTooltip > div")
WebElement checkMoreInfoIndicationForReferral;
@FindBy(css = ".indication_for_referral .xTooltip .hide-tool")
WebElement closeMoreInfoIndicationForReferral;
@FindBy(css = ".relatives-info .xHelpButton")
WebElement moreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .xTooltip > div")
WebElement checkMoreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .xTooltip .hide-tool")
WebElement closeMoreInfoNewEntryFamilyStudy;
@FindBy(css = ".relatives-info .list-actions .add-data-button")
WebElement newEntryFamilyStudy;
@FindBy(id = "PhenoTips.RelativeClass_0_relative_type")
WebElement thisPatientIsThe;
@FindBy(xpath = "//*[contains(@class, 'relatives-info')]//*[@class = 'relative_of']//*[@class = 'suggested']")
WebElement ofPatientWithIdentifier;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[contains(@class, 'family_history')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoFamilyHealthConditions;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[@class = 'xTooltip']")
WebElement checkMoreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset gestation ']//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoGestation;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[@class = 'xTooltip']")
WebElement checkMoreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[@class = 'fieldset global_age_of_onset ']//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoGlobalAgeOfOnset;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoNewEntryMeasurements;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoOMIMDisorder;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoOMIMDisorder;
@FindBy(xpath = "//*[contains(@class, 'diagnosis-info')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoOMIMDisorder;
@FindBy(id = "HYoumaywanttoinvestigate...")
WebElement youMayWantToInvestigate;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'fa-question-circle')]")
WebElement moreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'unaffected controller')]//*[@class = 'xTooltip']")
WebElement checkMoreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'phenotype-info')]//*[contains(@class, 'unaffected controller')]//*[@class = 'xTooltip']//*[@class = 'hide-tool']")
WebElement closeMoreInfoSelectObservedPhenotypes;
@FindBy(xpath = "//*[@class = 'browse-phenotype-categories']//*[@class = 'expand-tools'][@class = 'collapse-all']//*[@class = 'collapse-all']")
WebElement collapseAllPhenotypes;
@FindBy(xpath = "//*[@class = 'browse-phenotype-categories']//*[@class = 'expand-tools'][@class = 'collapse-all']//*[@class = 'expand-all']")
WebElement expandAllPhenotypes;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']")
WebElement chartTitleBoys;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, girls']")
WebElement chartTitleGirls;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, 2 to 20 years, boys']")
WebElement chartTitleOlderBoys;
@FindBy(id = "PhenoTips.MeasurementsClass_0_date")
WebElement dateOfMeasurments;
@FindBy(xpath = "//*[contains(@class, 'measurement-info')]//*[contains(@class, 'extradata-list')]//*[@class = 'age']//*[@class = 'age displayed-value']")
WebElement getAgeMeasurements;
@FindBy(xpath = "//*[@class = 'bottombuttons']//*[@class = 'button'][@name = 'action_save']")
WebElement saveAndViewButton;
@FindBy(xpath = "//*[@class = 'bottombuttons']//*[@class = 'button'][@name = 'action_saveandcontinue']")
WebElement saveAndContinueButton;
@FindBy(xpath = "//*[contains(@class, 'maternal_ethnicity')]//*[@class = 'hint']")
WebElement checkFamilyHistoryExpanded;
@FindBy(xpath = "//*[contains(@class, 'assistedReproduction_fertilityMeds ')]//*[@class = 'yes']")
WebElement assistedReproductionFertilityMedsYes;
@FindBy(xpath = "//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']")
WebElement checkIfGrowthChartsAreShowingByText;
// MINE
@FindBy(id = "PhenoTips.PatientClass_0_external_id")
WebElement patientIdentifier;
@FindBy(id = "body")
WebElement body;
/* Date of Birth */
/* Date of Death */
@FindBy(xpath = "//*[@class = 'calendar_date_select']//*[@class = 'year']")
WebElement setYearDateOfBirth;
@FindBy(css = ".fieldset.date_of_birth .fuzzy-date-picker")
WebElement birthDateSelector;
@FindBy(css = ".fieldset.date_of_death .fuzzy-date-picker")
WebElement deathDateSelector;
@FindBy(id = "PhenoTips.PatientClass_0_last_name")
WebElement patientLastName;
@FindBy(id = "PhenoTips.PatientClass_0_first_name")
WebElement patientFirstName;
@FindBy(id = "xwiki-form-gender-0-0")
WebElement patientGenderMale;
@FindBy(id = "xwiki-form-gender-0-1")
WebElement patientGenderFemale;
@FindBy(id = "xwiki-form-gender-0-2")
WebElement patientGenderOther;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0003745")
WebElement globalInheritanceSporadic;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0000006")
WebElement globalInheritanceAutosomal;
@FindBy(id = "PhenoTips.PatientClass_0_global_mode_of_inheritance_HP:0010982")
WebElement globalInheritancePolygenic;
@FindBy(id = "PhenoTips.PatientClass_0_gestation_term")
WebElement checkTermBirth;
// Assisted Reproduction
@FindBy(css = ".fieldset.assistedReproduction_fertilityMeds label.yes")
WebElement assistedReproductionFertilityYes;
@FindBy(css = ".fieldset.ivf label.no")
WebElement assistedReproductionInVitroNo;
// APGAR Scores
@FindBy(id = "PhenoTips.PatientClass_0_apgar1")
WebElement APGAROneMinute;
@FindBy(id = "PhenoTips.PatientClass_0_apgar5")
WebElement APGARFiveMinutes;
@FindBy(id = "PhenoTips.PatientClass_0_prenatal_development")
WebElement prenatalNotes;
@FindBy(id = "PhenoTips.PatientClass_0_prenatal_phenotype_HP:0001518")
WebElement prenatalGrowthSmallGestationalYes;
@FindBy(css = "label.yes[for=\"PhenoTips.PatientClass_0_prenatal_phenotype_HP:0003517\"]")
WebElement prenatalGrowthLargeBirthYes;
@FindBy(css = ".prenatal_phenotype-group #HPrenatal-growth-parameters ~ .prenatal_phenotype-other input.suggested")
WebElement prenatalGrowthOther;
@FindBy(css = "label.no[for=\"PhenoTips.PatientClass_0_negative_prenatal_phenotype_HP:0001561\"]")
WebElement prenatalDevelopmentPolyhydramniosNo;
@FindBy(css = ".prenatal_phenotype-group #HPrenatal-development-or-birth ~ .prenatal_phenotype-other input.suggested")
WebElement prenatalDevelopmentOther;
@FindBy(id = "PhenoTips.PatientClass_0_global_age_of_onset_HP:0003584")
WebElement lateOnset;
@FindBy(id = "PhenoTips.PatientClass_0_medical_history")
WebElement medicalHistory;
@FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular > tbody > tr.new > td.gene > input")
WebElement geneCandidateSearch;
@FindBy(id = "PhenoTips.InvestigationClass_0_comments")
WebElement geneCandidateComment;
@FindBy(css = ".chapter.genotype #extradata-list-PhenoTips\\2e InvestigationClass-molecular + .list-actions .add-data-button")
WebElement newEntryListOfCandidateGenes;
@FindBy(css = "#extradata-list-PhenoTips\\2e RejectedGenesClass > tbody > tr.new > td.gene > input")
WebElement genePreviously;
@FindBy(css = "#PhenoTips\\2e RejectedGenesClass_1_comments")
WebElement genePreviouslyTestedComment;
@FindBy(css = ".chapter.genotype #extradata-list-PhenoTips\\2e RejectedGenesClass + .list-actions .add-data-button")
WebElement newEntryPreviouslyTested;
@FindBy(id = "HCaseresolution")
WebElement caseResolutionSectionHeading;
@FindBy(id = "PhenoTips.PatientClass_0_solved")
WebElement caseSolved;
@FindBy(css = ".phenotype-info.chapter.collapsed > .expand-tools .show .tool")
WebElement clinicalSymptomsAndPhysicalFindings;
@FindBy(id = "PhenoTips.PatientClass_0_solved__pubmed_id")
WebElement pubmedID;
@FindBy(css = ".fieldset.solved__gene_id input.suggested")
WebElement geneID;
@FindBy(id = "PhenoTips.PatientClass_0_solved__notes")
WebElement resolutionNotes;
@FindBy(css = ".bottombuttons input[name=\"action_save\"]")
WebElement saveAndViewSummary;
public static PatientRecordEditPage gotoPage(String patientId)
{
getUtil().gotoPage("data", patientId, "edit");
return new PatientRecordEditPage();
}
public void clickBody()
{
this.body.click();
}
public String getPatientRecordId()
{
return this.recordId.getText();
}
/* PATIENT INFORMATION */
/**
* Sets the first and last name of the patient
*
* @param first patient first name
* @param last patient last name
*/
public void setPatientName(String first, String last)
{
// first name
this.patientLastName.clear();
this.patientLastName.sendKeys(first);
// last name
this.patientFirstName.clear();
this.patientFirstName.sendKeys(last);
}
/**
* Sets the full birthdate of the patient
*
* @param day the birthdate of the patient
* @param month the birthmonth of the patient
* @param year the birthyear of the patient
*/
public void setPatientDateOfBirth(String day, String month, String year)
{
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(1) > select")))
.selectByVisibleText(year);
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(2) > select")))
.selectByVisibleText(month);
new Select(this.birthDateSelector.findElement(By.cssSelector("span:nth-child(3) > select")))
.selectByVisibleText(day);
}
/**
* Sets the date of passing of the patient
*
* @param day the day of death of the patient
* @param month the month death of the patient
* @param year the year death of the patient
*/
public void setPatientDateOfDeath(String day, String month, String year)
{
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(1) > select")))
.selectByVisibleText(year);
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(2) > select")))
.selectByVisibleText(month);
new Select(this.deathDateSelector.findElement(By.cssSelector("span:nth-child(3) > select")))
.selectByVisibleText(day);
}
/**
* Sets the gender of the patient
*
* @param gender one of {@code male}, {@code female} or {@code other}
*/
public void setPatientGender(String gender)
{
if (gender == "male") {
this.patientGenderMale.click();
} else if (gender == "female") {
this.patientGenderFemale.click();
} else if (gender == "other") {
this.patientGenderOther.click();
}
this.body.click();
}
public void expandFamilyHistory()
{
this.familyHistorySectionHeading.click();
}
/**
* Creates a new entry for family studies
*
* @param relative type of relative; one of "Child", "Parent", "Sibling"... etc.
* @param relative_id the reference if of the relative in the system
*/
public void newEntryFamilyStudy(String relative, String relative_id)
{
// click new family study button
this.newEntryFamilyStudy.click();
// select the type of relative
// this.waitUntilElementIsVisible(By.id("PhenoTips.RelativeClass_0_relative_type"));
new Select(this.thisPatientIsThe).selectByVisibleText(relative);
// input the id of the relative
this.ofPatientWithIdentifier.clear();
this.ofPatientWithIdentifier.sendKeys(relative_id);
}
/**
* Sets ethnicities in Family History tab
*
* @param maternal the maternal ethnicity of the patient
* @param paternal the paternal ethnicity of the patient
*/
public void setEthnicites(String maternal, String paternal)
{
this.maternalEthnicity.clear();
this.maternalEthnicity.sendKeys(maternal);
this.paternalEthnicity.clear();
this.paternalEthnicity.sendKeys(paternal);
}
/**
* Checkboxes global mode of inheritance for autosomal, polygenic and sporadic
*/
public void setGlobalModeOfInheritance()
{
this.globalInheritanceAutosomal.click();
this.globalInheritancePolygenic.click();
this.globalInheritanceSporadic.click();
}
/* PRENETAL AND PERINATAL HISTORY */
public void expandPrenatalAndPerinatalHistory()
{
this.prenatalAndPerinatalHistorySectionHeading.click();
}
/**
* Sets prenatal gestration at birth text box and checks the term birth box if wanted
*
* @param weeks the number of weeks to input in the text box
*/
public void setPrenatalGestationAtDelivery(String weeks)
{
this.gestationAtDelivery.clear();
this.gestationAtDelivery.sendKeys(weeks);
}
/**
* Sets the yes and no values for assisted reproduction boxes
*/
public void setAssistedReproduction()
{
this.assistedReproductionFertilityYes.click();
this.assistedReproductionInVitroNo.click();
}
/**
* Sets APGAR scores from the one and five minute options
*
* @param oneMinute a string that this one of the numbers "1" to "10" or "Unknown" for the one minute APGAR
* @param fiveMinute a string that this one of the numbers "1" to "10" or "Unknown" for the five minute APGAR
*/
public void setAPGARScores(String oneMinute, String fiveMinutes)
{
// this.waitUntilElementIsVisible(By.id("PhenoTips.PatientClass_0_apgar1"));
new Select(this.APGAROneMinute).selectByVisibleText(oneMinute);
// this.waitUntilElementDisappears(By.id("PhenoTips.PatientClass_0_apgar5"));
new Select(this.APGARFiveMinutes).selectByVisibleText(fiveMinutes);
}
public void setPrenatalNotes(String notes)
{
this.prenatalNotes.clear();
this.prenatalNotes.sendKeys(notes);
}
/**
* Sets the prenatal growth parameters
*
* @param other the text to goes in the other text box
*/
public void setPrenatalGrowthParameters(String other)
{
// doesn't work, element isn't visible
this.prenatalGrowthSmallGestationalYes.click();
this.prenatalGrowthLargeBirthYes.click();
this.prenatalGrowthOther.clear();
this.prenatalGrowthOther.sendKeys();
}
/**
* Sets the prenatal developement or birth information
*
* @param other the text that goes in the other text box
*/
public void setPrenatalDevelopmentOrBirth(String other)
{
// doesn't work, element isn't visible
this.prenatalDevelopmentPolyhydramniosNo.click();
this.prenatalDevelopmentOther.clear();
this.prenatalDevelopmentOther.sendKeys(other);
}
/**
* Enters text in the "medical and developmental history text box
*
* @param history the text to be entered
*/
public void setMedicalHistory(String history)
{
this.medicalHistory.clear();
this.medicalHistory.sendKeys(history);
}
/**
* Clicks the radio button "Late onset" in the radio group of "Global age at onset" buttons
*/
public void setLateOnset()
{
this.lateOnset.click();
}
/**
* Returns the number of elements that match the css for the "upload image" button
*
* @return the number of elements matching this css
*/
public int findElementsUploadImage()
{
return getDriver()
.findElements(
By.cssSelector("#PhenoTips\\2e PatientClass_0_reports_history_container > div.actions > span > a"))
.size();
}
public void clickTermBirth()
{
this.checkTermBirth.click();
}
public void openNewEntryListOfCandidateGenes()
{
this.newEntryListOfCandidateGenes.click();
}
public int checkGeneCandidateSearchHideSuggestions(String search)
{
this.geneCandidateSearch.clear();
this.geneCandidateSearch.sendKeys(search);
return getDriver()
.findElements(By.cssSelector("#body > div.suggestItems.ajaxsuggest > div:nth-child(1) > span")).size();
}
public void setGeneCandidateComment(String comment)
{
this.geneCandidateComment.clear();
this.geneCandidateComment.sendKeys(comment);
}
public void openNewEntryPreviouslyTested()
{
this.newEntryPreviouslyTested.click();
}
public int checkGenePreviouslySearchHideSuggestions(String search)
{
this.genePreviously.clear();
this.genePreviously.sendKeys(search);
return getDriver()
.findElements(By.cssSelector("#body > div.suggestItems.ajaxsuggest > div:nth-child(1) > span")).size();
}
public void setPreviouslyTestedGenesComment(String comment)
{
this.genePreviouslyTestedComment.clear();
this.genePreviouslyTestedComment.sendKeys(comment);
}
public void expandCaseResolution()
{
this.caseResolutionSectionHeading.click();
}
public void setCaseSolved()
{
this.caseSolved.click();
}
public void setIDsAndNotes(String pID, String gID, String notes)
{
this.pubmedID.clear();
this.pubmedID.sendKeys(pID);
this.geneID.clear();
this.geneID.sendKeys(gID);
this.resolutionNotes.clear();
this.resolutionNotes.sendKeys(notes);
}
public void setPatientIdentifier(String value)
{
this.patientIdentifier.clear();
this.patientIdentifier.sendKeys(value);
}
public void familyHealthConditions(String value)
{
this.familyHealthConditions.clear();
this.familyHealthConditions.sendKeys(value);
}
public void expandMedicalHistory()
{
this.medicalHistorySectionHeading.click();
}
public void expandMeasurements()
{
this.measurementsSectionHeading.click();
}
public void createNewMeasurementsEntry()
{
this.newEntryMeasurements.click();
}
/* setting measurements */
public void setMeasurementWeight(String value)
{
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.MeasurementsClass_0_weight"));
this.measurementWeight.clear();
this.measurementWeight.click();
this.measurementWeight.sendKeys(value);
}
public void setMeasurementHeight(String value)
{
this.measurementHeight.clear();
this.measurementHeight.click();
this.measurementHeight.sendKeys(value);
}
public void setMeasurementArmSpan(String value)
{
this.measurementArmSpan.clear();
this.measurementArmSpan.click();
this.measurementArmSpan.sendKeys(value);
}
public void setMeasurementSittingHeight(String value)
{
this.measurementSittingHeight.clear();
this.measurementSittingHeight.click();
this.measurementSittingHeight.sendKeys(value);
}
public void setMeasurementHeadCircumference(String value)
{
this.measurementHeadCircumference.clear();
this.measurementHeadCircumference.sendKeys(value);
}
public void setMeasurementPhiltrumLength(String value)
{
this.measurementPhiltrumLength.clear();
this.measurementPhiltrumLength.sendKeys(value);
}
public void setMeasurementLeftEarLength(String value)
{
this.measurementLeftEarLength.clear();
this.measurementLeftEarLength.sendKeys(value);
}
public void setMeasurementRightEarLength(String value)
{
this.measurementRightEarLength.clear();
this.measurementRightEarLength.sendKeys(value);
}
public void setMeasurementOuterCanthalDistance(String value)
{
this.measurementOuterCanthalDistance.clear();
this.measurementOuterCanthalDistance.sendKeys(value);
}
public void setMeasurementInnerCanthalDistance(String value)
{
this.measurementInnerCanthalDistance.clear();
this.measurementInnerCanthalDistance.sendKeys(value);
}
public void setMeasuremtnePalpebralFissureLength(String value)
{
this.measurementPalpebralFissureLength.clear();
this.measurementPalpebralFissureLength.sendKeys(value);
}
public void setMeasurementInterpupilaryDistance(String value)
{
this.measurementInterpupilaryDistance.clear();
this.measurementInterpupilaryDistance.sendKeys(value);
}
public void setMeasurementLeftHandLength(String value)
{
this.measurementLeftHandLength.clear();
this.measurementLeftHandLength.sendKeys(value);
}
public void setMeasurementLeftPalmLength(String value)
{
this.measurementLeftPalmLength.clear();
this.measurementLeftPalmLength.sendKeys(value);
}
public void setMeasurementLeftFootLength(String value)
{
this.measurementLeftFootLength.clear();
this.measurementLeftFootLength.sendKeys(value);
}
public void setMeasurementRightHandLength(String value)
{
this.measurementRightHandLength.clear();
this.measurementRightHandLength.sendKeys(value);
}
public void setMeasurementRightPalmLength(String value)
{
this.measurementRightPalmLength.clear();
this.measurementRightPalmLength.sendKeys(value);
}
public void setMeasurementRightFootLength(String value)
{
this.measurementRightFootLength.clear();
this.measurementRightFootLength.sendKeys(value);
}
public boolean checkIfGrowthChartsAreShowing()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, boys']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public String checkIfGrowthChartsAreShowingByText()
{
return this.checkIfGrowthChartsAreShowingByText.getText();
}
public void expandGenotypeInformation()
{
this.genotypeInformationSectionHeading.click();
}
///////////////////////////////////
// public void setGenotypeInformationComments(String value)
// {
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.InvestigationClass_0_comments"));
// this.genotypeInformationComments.clear();
// this.genotypeInformationComments.sendKeys(value);
// }
// public void setGenotypeInformationGene(String value)
// {
// this.genotypeInformationGene.clear();
// this.genotypeInformationGene.sendKeys(value);
// }
public void setPatientClinicallyNormal()
{
this.patientIsClinicallyNormal.click();
}
public void expandClinicalSymptomsAndPhysicalFindings()
{
this.clinicalSymptomsAndPhysicalFindings.click();
}
public boolean checkIfClinicalSymptomsAndPhysicalFindingsExpanded(By by)
{
try {
getDriver().findElement(By.id("PhenoTips.PatientClass_0_unaffected"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void selectPhenotype(String id, boolean positive)
{
BaseElement
.getUtil()
.findElementWithoutWaiting(
getDriver(),
By.cssSelector("label[for='PhenoTips.PatientClass_0_" + (positive ? "" : "negative_") + "phenotype_"
+ id + "']")).click();
;
}
public void setHypotelorismYes()
{
selectPhenotype("HP:0000601", true);
}
public void setStature3rdPercentile()
{
selectPhenotype("HP:0004322", true);
}
public void setWeight3rdPercentile()
{
selectPhenotype("HP:0004325", true);
}
public void setHeadCircumference3rdPercentile()
{
selectPhenotype("HP:0000252", true);
}
public void setHemihypertrophyYes()
{
selectPhenotype("HP:0001528", true);
}
public void setCraniosynostosisYes()
{
selectPhenotype("HP:0001363", true);
}
public void setCleftUpperLipNO()
{
selectPhenotype("HP:0000204", false);
}
public void setCleftPalateYes()
{
selectPhenotype("HP:0000175", true);
}
public void setAbnormalFacialShapeYes()
{
selectPhenotype("HP:0001999", true);
}
public void setVisualImpairmentYes()
{
selectPhenotype("HP:0000505", true);
}
public void setAbnormalityOfTheCorneaNO()
{
selectPhenotype("HP:0000481", false);
}
public void setColobomaNO()
{
selectPhenotype("HP:0000589", false);
}
public void setSensorineuralNO()
{
selectPhenotype("HP:0000407", false);
}
public void setAbnormalityOfTheInnerEarYes()
{
selectPhenotype("HP:0000359", true);
}
public void setHyperpigmentationOfTheSkinYes()
{
selectPhenotype("HP:0000953", true);
}
public void setCapillaryHemangiomasNO()
{
selectPhenotype("HP:0005306", false);
}
public void setVentricularSeptalDefectNO()
{
selectPhenotype("HP:0001629", false);
}
public void setArrhythmiaYes()
{
selectPhenotype("HP:0011675", true);
}
public void setCongenitalDiaphragmaticHerniaYes()
{
selectPhenotype("HP:0000776", true);
}
public void setAbnormalityOfTheLungNO()
{
selectPhenotype("HP:0002088", false);
}
public void setLowerLimbUndergrowthYes()
{
selectPhenotype("HP:0009816", true);
}
public void setScoliosisYes()
{
selectPhenotype("HP:0002650", true);
}
public void setAbnormalityOfTheVertebralColumnNO()
{
selectPhenotype("HP:0000925", false);
}
public void setCholestasisYes()
{
selectPhenotype("HP:0001396", true);
}
public void setDiabetesMellitusNO()
{
selectPhenotype("HP:0000819", false);
}
public void setHorseshoeKidneyNO()
{
selectPhenotype("HP:0000085", false);
}
public void setHypospadiasYes()
{
selectPhenotype("HP:0000047", true);
}
public void setDelayedFineMotorDevelopmentYes()
{
selectPhenotype("HP:0010862", true);
}
public void setAttentionDeficitHyperactivityDisorderNO()
{
selectPhenotype("HP:0007018", false);
}
public void setAustismYes()
{
selectPhenotype("HP:0000717", true);
}
public void setSeizuresYes()
{
selectPhenotype("HP:0001250", true);
}
public void setSpinalDysraphismNO()
{
selectPhenotype("HP:0010301", false);
}
public void coarctationOfAortaDropDown()
{
this.coarctationOfAortaDropDown.click();
}
public String checkCoarctationOfAortaDropDown()
{
return this.checkCoarctationOfAortaDropDown.getText();
}
public void hemihypertrophyAddDetails()
{
this.hemihypertrophyAddDetails.click();
}
public void ageOfOnsetHemihypertrophy()
{
this.ageOfOnsetHemihypertrophy.click();
}
public void setNeonatalOnsetHemihypertrophy()
{
this.neonatalOnsetHemihypertrophy.click();
}
public void temporalPatternHemihypertrophy()
{
this.temporalPatternHemihypertrophy.click();
}
public void setSubacuteTemporalPatternHemihypertrophy()
{
this.subacuteTemporalPatternHemihypertrophy.click();
}
public void deleteCleftPalate()
{
this.deleteCleftPalate.click();
}
public void abnormalFacialShapeAddDetails()
{
this.abnormalFacialShapeAddDetails.click();
}
public void paceOfProgressionAbnormalFacialShape()
{
this.paceOfProgressionAbnormalFacialShape.click();
}
public void slowPaceOfProgressionAbnormalFacialShape()
{
this.slowPaceOfProgressionAbnormalFacialShape.click();
}
public void hypotelorismAddDetails()
{
this.hypotelorismAddDetails.click();
}
public void severityHypotelorism()
{
this.severityHypotelorism.click();
}
public void moderateSeverityHypotelorism()
{
this.moderateSeverityHypotelorism.click();
}
public void abnormalityOfTheInnerEarAddDetails()
{
this.abnormalityOfTheInnerEarAddDetails.click();
}
public void spatialPatternAbnormalityOfTheInnerEar()
{
this.spatialPatternAbnormalityOfTheInnerEar.click();
}
public void distalSpatialPatternAbnomalityOfTheInnerEar()
{
this.distalSpatialPatternAbnormalityOfTheInnerEar.click();
}
public void arrythmiaAddDetails()
{
this.arrhythmiaAddDetails.click();
}
public void arrythmiaComments(String value)
{
this.arrhythmiaComments.clear();
this.arrhythmiaComments.sendKeys(value);
}
public void scoliosisAddDetails()
{
this.scoliosisAddDetails.click();
}
public void lateralityScoliosis()
{
this.lateralityScoliosis.click();
}
public void rightLateralityScoliosis()
{
this.rightLateralityScoliosis.click();
}
public void seizuresAddDetails()
{
this.seizuresAddDetails.click();
}
public void severitySeizures()
{
this.severitySeizures.click();
}
public void mildSeveritySeizures()
{
this.mildSeveritySeizures.click();
}
public void asymmetryOfTheEarsYes()
{
this.asymmetryOfTheEarsYes.click();
}
public void immunodeficiencyYes()
{
this.immunodeficiencyYes.click();
}
public void abnormalityOfTheCartoidArteriesYes()
{
this.abnormalityOfTheCartoidArteriesYes.click();
}
public void bifidTongueYes()
{
this.bifidTongueYes.click();
}
public void bifidRibsYes()
{
this.bifidRibsYes.click();
}
public void hypsarrhythmiaNO()
{
this.hypsarrhythmiaNO.click();
}
public void phenotypeQuickSearch(String value)
{
this.phenotypeQuickSearch.clear();
this.phenotypeQuickSearch.sendKeys(value);
}
public void quickSearchCataractYes()
{
this.quickSearchCataractYes.click();
}
public void expandDiagnosis()
{
this.diagnosisSectionHeading.click();
}
public void setDiagnosisAdditionalComments(String value)
{
this.diagnosisAdditionalComments.clear();
this.diagnosisAdditionalComments.sendKeys(value);
}
public void setSmithLemliOptizSyndrome()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__270400"));
this.smithLemliOptizSyndrome.click();
}
public void setWatsonSyndrome()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__193520"));
this.watsonSyndrome.click();
}
public void setIndicationForReferral(String value)
{
this.indicationForReferral.clear();
this.indicationForReferral.sendKeys(value);
}
public void setPrenatalGrowthPatternsOther(String value)
{
this.prenatalGrowthPatternsOther.clear();
this.prenatalGrowthPatternsOther.sendKeys(value);
}
public void setPositvieFerricChlorideTestYes()
{
this.positiveFerricChlorideTestYes.click();
}
public void setPrenatalDevelopmentOrBirthOther(String value)
{
this.prenatalDevelopmentOrBirthOther.clear();
this.prenatalDevelopmentOrBirthOther.sendKeys(value);
}
public void setDysplasticTestesYes()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'resultContainer']//*[@class = 'yes'][//input[@value = 'HP:0008733']]"));
this.dysplasticTestesYes.click();
}
public String getWeightPctl()
{
return this.weightPctl.getText();
}
public String getHeightPctl()
{
return this.heightPctl.getText();
}
public String getBMIPctl()
{
return this.bmiPctl.getText();
}
public String getSittingPctl()
{
return this.sittingPctl.getText();
}
public String getHeadCircumferencePctl()
{
return this.headCircumferencePctl.getText();
}
public String getPhiltrumPctl()
{
return this.philtrumPctl.getText();
}
public String getLeftEarPctl()
{
return this.leftEarPctl.getText();
}
public String getRightEarPctl()
{
return this.rightEarPctl.getText();
}
public String getOuterCanthalPctl()
{
return this.outerCanthalPctl.getText();
}
public String getInnerCanthalPctl()
{
return this.innerCanthalPctl.getText();
}
public String getPalpebralFissurePctl()
{
return this.palpebralFissurePctl.getText();
}
public String getInterpupilaryPctl()
{
return this.interpupilaryPctl.getText();
}
public String getLeftPalmPctl()
{
return this.leftPalmPctl.getText();
}
public String getLeftFootPctl()
{
return this.leftFootPctl.getText();
}
public String getRightPalmPctl()
{
return this.rightPalmPctl.getText();
}
public String getRightFootPctl()
{
return this.rightFootPctl.getText();
}
public String getBMINumber()
{
return this.bmiNumber.getText();
}
public void setOMIMDisorder(String value)
{
this.OMIMDisorderBar.clear();
this.OMIMDisorderBar.sendKeys(value);
}
public void setOMIMDisorderWolfSyndrome()
{
this.OMIMDisorderWolfSyndrome.click();
}
public void excludeLowerLimbUndergrowth()
{
this.OMIMBoxLowerLimbUnderGrowth.click();
}
public String checkLowerLimbUndergrowthExcluded()
{
return this.OMIMBoxLowerLimbUnderGrowthExcluded.getText();
}
public String checkSmithLemliInOMIM()
{
return this.checkSmithLemliInOMIM.getText();
}
public void setCriDuChatSyndromeFromBottom()
{
// this.getDriver().waitUntilElementIsVisible(By.id("result__123450"));
this.criDuChatSyndrome.click();
}
public String checkCriDuChatAppears()
{
return this.checkCriDuChatAppears.getText();
}
public boolean checkCriDuChatDisappearsFromTop(By by)
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'fieldset omim_id']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][@value = '123450']//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStatureLightningBoltAppearsOnRight()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-item'][.//input[@value = 'HP:0004322']]//*[contains(@class, 'fa-bolt')]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkHypotelorismLightningBoltAppearsOnRight()
{
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-item'][.//input[@value = 'HP:0000601']]//*[contains(@class, 'fa-bolt')]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkCriDuChatDisappearsFromBottom()
{
getDriver()
.findElement(
By.xpath(
"//*[@class = 'fieldset omim_id ']//*[@class = 'displayed-value']//*[@class = 'accepted-suggestion'][@value = '123450']//*[@class = 'value'][text()='#123450 CRI-DU-CHAT SYNDROME ']"))
.isSelected();
return true;
}
public void setCriDuChatFromTop()
{
// this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.PatientClass_0_omim_id_123450"));
this.criDuChatOMIMTop.click();
}
public void setPreauricularPitYes()
{
selectPhenotype("HP:0004467", true);
}
public boolean checkPreauricularPitAppearsOnRight()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0004467']]//*[@class =
// 'yes'][text() = 'Preauricular pit']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0004467']]//*[@class = 'yes'][text() = 'Preauricular pit']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void setNystagmusNO()
{
selectPhenotype("HP:0000639", false);
}
public boolean checkNystagmusAppearsOnRightNO()
{
// this.getDriver().waitUntilElementIsVisible(By
// .xpath("//*[@class = 'summary-item'][//label[@class = 'no']][//input[@value = 'HP:0000639']]//*[@class =
// 'no'][text() = 'Nystagmus']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'no']][//input[@value = 'HP:0000639']]//*[@class = 'no'][text() = 'Nystagmus']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkNystagmusReturnsToNA()
{
try {
return getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'term-entry')][.//*[@value = 'HP:0000639']]//label[contains(@class, 'na')]"))
.getAttribute("class").contains("selected");
} catch (NoSuchElementException e) {
return false;
}
}
public void deleteNystagmusFromRight()
{
this.deleteNystagmusRight.click();
}
public boolean checkPolyphagiaDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@class = 'background-search']//*[@class = 'phenotype'][//label[@class = 'yes']][//input[@value = 'HP:0002591']]//*[@class = 'initialized']//*[@class = 'yes-no-picker-label'][text() = 'polyphagia']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'background-search']//*[@class = 'phenotype'][//label[@class = 'yes']][//input[@value = 'HP:0002591']]//*[@class = 'initialized']//*[@class = 'yes-no-picker-label'][text() = 'polyphagia']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkImmunodeficiencyDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0002721']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkAbnormalityOfTheCartoidArteriesDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0005344']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkBifidTongueDissapearsFromRightInvestigateBox()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010297']]"));
try {
return !getUtil()
.hasElement(
By.xpath(
"//*[contains(@class, 'background-search')]//label[contains(@class, 'yes')][.//input[@value = 'HP:0010297']]"));
} catch (NoSuchElementException e) {
return false;
}
}
public void polyphagiaYes()
{
this.polyphagiaYes.click();
}
public void browseRelatedTermsCataract()
{
this.getDriver()
.findElement(
By.xpath(
"//*[contains(@class, 'suggestItems')]//*[contains(@class, 'suggestItem')][//*[text() = 'Cataract']]//*[contains(@class, 'xHelpButton')]"))
.click();
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'resultContainer']//li[contains(@class, 'xitem')]//*[contains(@class, 'xTooltip')]//*[contains(text(), 'Browse related terms')]"));
this.browseRelatedTermsCataract.click();
}
public void abnormalityOfTheLensGoUP()
{
this.abnormalityOfTheLensGoUp.click();
}
public String abnormalityOfTheAnteriorSegmentOfTheEye()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'ontology-tree']//*[@class = 'entry parent']//*[@class = 'value'][text() = 'Abnormality of the anterior segment of the eye']"));
return this.abnormalityOfTheAnteriorSegmentOfTheEyeCheck.getText();
}
public void phacodonesisYes()
{
this.phacodonesisYes.click();
}
public void closeBrowseRelatedTerms()
{
this.closeBrowseRelatedTerms.click();
}
public void hideQuickSearchBarSuggestions()
{
this.hideQuickSearchBarSuggestions.click();
}
public boolean checkPhacodonesisAppearsOnRight()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0012629']]//*[@class = 'yes'][text() = 'Phacodonesis']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'summary-item'][//label[@class = 'yes']][//input[@value = 'HP:0012629']]//*[@class = 'yes'][text() = 'Phacodonesis']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void openDateOfMeasurements()
{
this.dateOfMeasurments.click();
}
public void setDate1()
{
this.date1.click();
}
public void setDate12()
{
this.date12.click();
}
public void setGastroschisisYes()
{
selectPhenotype("HP:0001543", true);
}
public boolean checkSmithLemliSyndrome()
{
this.getDriver().waitUntilElementIsVisible(By.id("result__270400"));
try {
getDriver().findElement(By.id("result__270400"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void moreInfoHypotelorism()
{
this.moreInfoHypotelorism.click();
}
public String checkMoreInfoOpened()
{
return this.checkMoreInfoHypotelorismOpened.getText();
}
public void closeMoreInfoHypotelorism()
{
this.closeMoreInfoHypotelorism.click();
}
public void moreInfoSex()
{
this.moreInfoSex.click();
}
public String checkMoreInfoSex()
{
return this.checkMoreInfoSex.getText();
}
public void closeMoreInfoSex()
{
this.closeMoreInfoSex.click();
}
public void moreInfoIndicationForReferral()
{
this.moreInfoIndicationForReferral.click();
}
public String checkMoreInfoIndicationForReferral()
{
return this.checkMoreInfoIndicationForReferral.getText();
}
public void closeMoreInfoIndicationForReferral()
{
this.closeMoreInfoIndicationForReferral.click();
}
public void moreInfoNewEntryFamilyStudy()
{
this.moreInfoNewEntryFamilyStudy.click();
}
public String checkMoreInfoFamilyStudy()
{
return this.checkMoreInfoNewEntryFamilyStudy.getText();
}
public void closeMoreInfoNewEntryFamilyStudy()
{
this.closeMoreInfoNewEntryFamilyStudy.click();
}
public void setPatientIsTheRelativeOf(String relative)
{
this.getDriver().waitUntilElementIsVisible(By.id("PhenoTips.RelativeClass_0_relative_type"));
new Select(this.thisPatientIsThe).selectByVisibleText(relative);
}
public void relativeOfCurrentPatient(String value)
{
this.ofPatientWithIdentifier.clear();
this.ofPatientWithIdentifier.sendKeys(value);
}
public void moreInfoFamilyHealthConditions()
{
this.moreInfoFamilyHealthConditions.click();
}
public String checkMoreInfoFamilyHealthConditions()
{
return this.checkMoreInfoFamilyHealthConditions.getText();
}
public void closeMoreInfoFamilyHealthConditions()
{
this.closeMoreInfoFamilyHealthConditions.click();
}
public void moreInfoGestation()
{
this.moreInfoGestation.click();
}
public String checkMoreInfoGestation()
{
return this.checkMoreInfoGestation.getText();
}
public void closeMoreInfoGestation()
{
this.closeMoreInfoGestation.click();
}
public void moreInfoGlobalAgeOfOnset()
{
this.moreInfoGlobalAgeOfOnset.click();
}
public String checkMoreInfoGlobalAgeOfOnset()
{
return this.checkMoreInfoGlobalAgeOfOnset.getText();
}
public void closeMoreInfoGlobalAgeOfOnset()
{
this.closeMoreInfoGlobalAgeOfOnset.click();
}
public void moreInfoNewEntryMeasurements()
{
this.moreInfoNewEntryMeasurements.click();
}
public String checkMoreInfoNewEntryMeasurements()
{
return this.checkMoreInfoNewEntryMeasurements.getText();
}
public void closeMoreInfoNewEntryMeasurements()
{
this.closeMoreInfoNewEntryMeasurements.click();
}
public void moreInfoOMIMDisorder()
{
this.moreInfoOMIMDisorder.click();
}
public String checkMoreInfoOMIMDisorder()
{
return this.checkMoreInfoOMIMDisorder.getText();
}
public void closeMoreInfoOMIMDisorder()
{
this.closeMoreInfoOMIMDisorder.click();
}
public void hideYouMayWantToInvestigate()
{
this.youMayWantToInvestigate.click();
}
public boolean checkYouMayWantToInvestigateHid()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@class = 'background-suggestions]//*[@class = 'phenotype'][@class = 'yes'][//input[@value = 'HP:0000878']]//*[@class = 'yes-no-picker']"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@class = 'background-suggestions]//*[@class = 'phenotype'][@class = 'yes'][//input[@value = 'HP:0000878']]//*[@class = 'yes-no-picker']"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void moreInfoSelectObservedPhenotypes()
{
this.moreInfoSelectObservedPhenotypes.click();
}
public String checkMoreInfoSelectObservedPhenotypes()
{
return this.checkMoreInfoSelectObservedPhenotypes.getText();
}
public void closeMoreInfoSelectObservedPhenotypes()
{
this.closeMoreInfoSelectObservedPhenotypes.click();
}
public void collapseAllPhenotypes()
{
this.collapseAllPhenotypes.click();
}
public boolean checkAllPhenotypesCollapsed()
{
this.getDriver().waitUntilElementDisappears(
By.cssSelector("label[for='PhenoTips.PatientClass_0_phenotype_HP:0001363]"));
try {
getDriver().findElement(By.cssSelector("label[for='PhenoTips.PatientClass_0_phenotype_HP:0001363]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void expandAllPhenotypes()
{
this.expandAllPhenotypes.click();
}
public void setYearDateOfBirth(String year)
{
new Select(this.setYearDateOfBirth).selectByVisibleText(year);
}
public void setYearMeasurement(String year)
{
new Select(this.setYearDateOfBirth).selectByVisibleText(year);
}
public void setMonthDateOfBirth(String month)
{
new Select(this.setMonthDate).selectByVisibleText(month);
}
public void setMonthMeasurement(String month)
{
new Select(this.setMonthDate).selectByVisibleText(month);
}
public boolean checkDecreasedBodyWeight()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkDecreasedBodyWeightDisappears()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004325']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStature()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public boolean checkShortStatureDisappears()
{
this.getDriver().waitUntilElementDisappears(By
.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
try {
getDriver()
.findElement(
By.xpath(
"//*[@id = 'current-phenotype-selection']//*[@class = 'summary-group']//*[@class = 'yes'][.//input[@value = 'HP:0004322']]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public String checkChartTitleChangesMale()
{
return this.chartTitleBoys.getText();
}
public String checkChartTitleChangesFemale()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath(
"//*[contains(@class, 'growth-charts-section')]//*[@id = 'charts']//*[contains(@class, 'chart-wrapper')]//*[text() = 'Weight for age, birth to 36 months, girls']"));
return this.chartTitleGirls.getText();
}
public String checkChartTitleChangesOlderMale()
{
this.getDriver().waitUntilElementIsVisible(By
.xpath("//*[@class = 'chart-title'][text() = 'Weight for age, 2 to 20 years, boys']"));
return this.chartTitleOlderBoys.getText();
}
@Override
public PatientRecordViewPage clickSaveAndView()
{
this.saveAndViewButton.click();
return new PatientRecordViewPage();
}
@Override
public void clickSaveAndContinue()
{
this.saveAndContinueButton.click();
}
public String getAgeMeasurements()
{
return this.getAgeMeasurements.getText();
}
@SuppressWarnings("unchecked")
@Override
protected PatientRecordViewPage createViewPage()
{
return new PatientRecordViewPage();
}
@Override
public void waitUntilPageJSIsLoaded()
{
getDriver().waitUntilJavascriptCondition("return window.Prototype != null && window.Prototype.Version != null");
}
}
| [cleanup] Better pageobjects selectors
| components/patient-data/pageobjects/src/main/java/org/phenotips/data/test/po/PatientRecordEditPage.java | [cleanup] Better pageobjects selectors | <ide><path>omponents/patient-data/pageobjects/src/main/java/org/phenotips/data/test/po/PatientRecordEditPage.java
<ide> @FindBy(id = "PhenoTips.PatientClass_0_medical_history")
<ide> WebElement medicalHistory;
<ide>
<del> @FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular > tbody > tr.new > td.gene > input")
<add> @FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular td.gene input[name=\"PhenoTips.InvestigationClass_0_gene\"]")
<ide> WebElement geneCandidateSearch;
<ide>
<del> @FindBy(id = "PhenoTips.InvestigationClass_0_comments")
<add> @FindBy(css = "#extradata-list-PhenoTips\\2e InvestigationClass-molecular td.comments textarea[name=\"PhenoTips.InvestigationClass_0_comments\"]")
<ide> WebElement geneCandidateComment;
<ide>
<ide> @FindBy(css = ".chapter.genotype #extradata-list-PhenoTips\\2e InvestigationClass-molecular + .list-actions .add-data-button") |
|
Java | apache-2.0 | f64b640cbdb917be7a4b94163a8c217b180cf8e7 | 0 | petermr/ami-chem,petermr/ami-chem,AndyHowlett/ami-chem,AndyHowlett/ami-chem | package org.xmlcml.ami2.chem;
import java.awt.Graphics2D;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import javax.imageio.ImageIO;
import nu.xom.Nodes;
import org.apache.commons.math.complex.Complex;
import org.apache.log4j.Logger;
import org.xmlcml.ami2.chem.Joinable.JoinPoint;
import org.xmlcml.ami2.chem.JoinableText.AreInSameStringDetector;
import org.xmlcml.ami2.chem.svg.SVGContainerNew;
import org.xmlcml.diagrams.OCRManager;
import org.xmlcml.euclid.Angle;
import org.xmlcml.euclid.Angle.Units;
import org.xmlcml.euclid.Line2;
import org.xmlcml.euclid.Real;
import org.xmlcml.euclid.Real2;
import org.xmlcml.euclid.Real2Array;
import org.xmlcml.euclid.Real2Range;
import org.xmlcml.euclid.RealRange;
import org.xmlcml.graphics.svg.SVGCircle;
import org.xmlcml.graphics.svg.SVGConstants;
import org.xmlcml.graphics.svg.SVGElement;
import org.xmlcml.graphics.svg.SVGG;
import org.xmlcml.graphics.svg.SVGImage;
import org.xmlcml.graphics.svg.SVGLine;
import org.xmlcml.graphics.svg.SVGPath;
import org.xmlcml.graphics.svg.SVGPolygon;
import org.xmlcml.graphics.svg.SVGSVG;
import org.xmlcml.graphics.svg.SVGTSpan;
import org.xmlcml.graphics.svg.SVGText;
import org.xmlcml.svgbuilder.geom.SimpleBuilder;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.UnionFind;
import com.google.common.util.concurrent.UncheckedTimeoutException;
//import net.sourceforge.tess4j.Tesseract;
//import net.sourceforge.tess4j.TesseractException;
/**
* Builds higher-level primitives from SVGPaths, SVGLines, etc. to create SVG objects
* such as TramLine and (later) Arrow.
*
* <p>SimpleBuilder's main function is to:
* <ul>
* <li>Read a raw SVG object and make lists of SVGPath and SVGText (and possibly higher levels ones
* if present).</li>
* <li>Turn SVGPaths into SVGLines , etc..</li>
* <li>Identify Junctions (line-line, line-text, and probably more).</li>
* <li>Join lines where they meet into higher level objects (TramLines, SVGRect, crosses, arrows, etc.).</li>
* <li>Create topologies (e.g. connection of lines and Junctions).</li>
* </ul>
*
* SimpleBuilder uses the services of the org.xmlcml.graphics.svg.path package and may later use
* org.xmlcml.graphics.svg.symbol.
* </p>
*
* <p>Input may either be explicit SVG primitives (e.g. <svg:rect>, <svg:line>) or
* implicit ones (<svg:path>) that can be interpreted as the above. The input may be either or
* both - we can't control it. The implicit get converted to explicit and then merged with the
* explicit:
* <pre>
* paths-> implicitLineList + rawLinelist -> explicitLineList
* </pre>
* </p>
*
* <h3>Strategy</h3>
* <p>createHigherLevelPrimitives() carries out the complete chain from svgRoot to the final
* primitives. Each step tests to see whether the result of the previous is null.
* If so it creates a non-null list and fills it if possible. </p>
*
* UPDATE: 2013-10-23 Renamed to "SimpleGeometryManager" as it doesn't deal with Words (which
* require TextStructurer). It's possible the whole higher-level primitive stuff should be removed to another
* project.
*
* @author pm286
*/
public class ChemistryBuilder extends SimpleBuilder {
private final static Logger LOG = Logger.getLogger(ChemistryBuilder.class);
private ChemistryBuilderParameters parameters = new ChemistryBuilderParameters();
protected HigherPrimitives higherPrimitives;
protected SVGContainerNew input;
//HashBiMap<HatchedBond, SVGLine> mutuallyExclusivePairs;
//Map<SVGLine, SingleBond> whichLineIsWhichSingleBond;
private List<JoinableText> atomLabelTexts;
private Map<Real2Range, Integer> atomLabelPositionsAndNumbers;
List<WedgeBond> wedgeBonds = new ArrayList<WedgeBond>();
private double scale = 1;
static class MutuallyExclusiveShortLineTriple {
HatchedBond hatchedBond;
Charge minus;
SVGLine line;
SingleBond singleBond;
public MutuallyExclusiveShortLineTriple(HatchedBond hatchedBond, Charge minus, SVGLine line) {
this.hatchedBond = hatchedBond;
this.minus = minus;
this.line = line;
}
}
static class MutuallyExclusiveShortLinePairTriple {
HatchedBond hatchedBond;
SVGLine line1;
SVGLine line2;
DoubleBond doubleBond;
SingleBond singleBond1;
SingleBond singleBond2;
public MutuallyExclusiveShortLinePairTriple(HatchedBond hatchedBond, SVGLine line1, SVGLine line2) {
this.hatchedBond = hatchedBond;
this.line1 = line1;
this.line2 = line2;
}
}
static class MutuallyExclusiveLinePairPair {
SVGLine line1;
SVGLine line2;
DoubleBond doubleBond;
SingleBond singleBond1;
SingleBond singleBond2;
public MutuallyExclusiveLinePairPair(DoubleBond doubleBond) {
this.line1 = doubleBond.getLine(0);
this.line2 = doubleBond.getLine(1);
this.doubleBond = doubleBond;
}
}
List<MutuallyExclusiveShortLineTriple> mutuallyExclusiveShortLineTriples;
List<MutuallyExclusiveShortLinePairTriple> mutuallyExclusiveShortLinePairTriples;
List<MutuallyExclusiveLinePairPair> mutuallyExclusiveLinePairPairs;
public ChemistryBuilder(SVGContainerNew svgRoot, long timeout, ChemistryBuilderParameters parameters) {
super((SVGElement) svgRoot.getElement(), timeout);
input = svgRoot;
this.parameters = parameters;
}
public ChemistryBuilder(SVGContainerNew svgRoot, ChemistryBuilderParameters parameters) {
super((SVGElement) svgRoot.getElement());
input = svgRoot;
this.parameters = parameters;
}
public ChemistryBuilder(SVGElement svgRoot, long timeout, ChemistryBuilderParameters parameters) {
super(svgRoot, timeout);
this.parameters = parameters;
}
public ChemistryBuilder(SVGElement svgRoot, ChemistryBuilderParameters parameters) {
super(svgRoot);
this.parameters = parameters;
}
public ChemistryBuilder(SVGContainerNew svgRoot, long timeout) {
super((SVGElement) svgRoot.getElement(), timeout);
input = svgRoot;
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGContainerNew svgRoot) {
super((SVGElement) svgRoot.getElement());
input = svgRoot;
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGElement svgRoot, long timeout) {
super(svgRoot, timeout);
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGElement svgRoot) {
super(svgRoot);
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilderParameters getParameters() {
return parameters;
}
public SVGContainerNew getInputContainer() {
return input;
}
/**
* Complete processing chain for low-level SVG into high-level SVG and non-SVG primitives such as double bonds.
* <p>
* Creates junctions.
* <p>
* Runs createDerivedPrimitives().
*
* @throws TimeoutException
*/
public void createHigherPrimitives() {
if (higherPrimitives == null) {
startTiming();
createDerivedPrimitives();
replaceTextImagesWithText();
splitMultiCharacterTexts();
higherPrimitives = new HigherPrimitives();
higherPrimitives.addSingleLines(derivedPrimitives.getLineList());
handleShortLines();
createDoubleBondList();
//createWords();
createJunctions();
}
}
@Override
protected void removeNearDuplicateAndObscuredPrimitives() {
double scale = parameters.setStandardBondLengthFromSVG(derivedPrimitives.getLineList());
nearDuplicateLineRemovalDistance *= (scale / this.scale);
nearDuplicatePolygonRemovalDistance *= (scale / this.scale);
minimumCutObjectGap *= (scale / this.scale);
maximumCutObjectGap *= (scale / this.scale);
this.scale = scale;
super.removeNearDuplicateAndObscuredPrimitives();
}
private void splitMultiCharacterTexts() {
Iterator<SVGText> it = derivedPrimitives.getTextList().iterator();
List<SVGText> newTexts = new ArrayList<SVGText>();
while (it.hasNext()) {
SVGText text = it.next();
String string = text.getText();
List<SVGTSpan> spanList = new ArrayList<SVGTSpan>();
double totalWidth = 0;
if (string == null) {
Nodes spans = text.query("svg:tspan", SVGSVG.SVG_XPATH);
for (int i = 0; i < spans.size(); i++) {
SVGTSpan span = (SVGTSpan) spans.get(i);
spanList.add(span);
GlyphVector v = span.getGlyphVector();
totalWidth += v.getLogicalBounds().getWidth();
if (span.getAttributeValue("dx") != null) {
totalWidth += Double.parseDouble(span.getAttributeValue("dx"));
}
}
} else {
spanList.add(new SVGTSpan(text));
totalWidth = text.getGlyphVector().getLogicalBounds().getWidth();
}
it.remove();
double previousX = text.getX() - ("end".equals(text.getAttributeValue("text-anchor")) ? totalWidth : 0);
double previousY = text.getY();
for (SVGTSpan span : spanList) {
if (span.getX() != 0.0) {
previousX = span.getX() - ("end".equals(text.getAttributeValue("text-anchor")) ? totalWidth : 0);
}
if (span.getY() != 0.0) {
previousY = span.getY();
}
GlyphVector glyphVector = span.getGlyphVector();
String spanText = span.getText();
for (int i = 0; i < spanText.length(); i++) {
String substring = spanText.substring(i, i + 1);
SVGText newText = new SVGText(new Real2(0, 0), substring);
newTexts.add(newText);
newText.copyAttributesFrom(span);
double dX = 0;
if (span.getAttributeValue("dx") != null) {
dX = Double.parseDouble(span.getAttributeValue("dx"));
newText.removeAttribute(newText.getAttribute("dx"));
}
double dY = 0;
if (span.getAttributeValue("dy") != null) {
dY = Double.parseDouble(span.getAttributeValue("dy"));
newText.removeAttribute(newText.getAttribute("dy"));
}
newText.setX(previousX + dX + glyphVector.getGlyphPosition(i).getX());
newText.setY(previousY + dY + glyphVector.getGlyphPosition(i).getY());
}
previousX += glyphVector.getGlyphPosition(glyphVector.getNumGlyphs()).getX();
if (span.getAttributeValue("dy") != null) {
previousY += Double.parseDouble(span.getAttributeValue("dy"));
}
}
}
derivedPrimitives.getTextList().addAll(newTexts);
}
public BufferedImage flipHorizontally(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(w, h, img.getColorModel().getTransparency());
Graphics2D g = dimg.createGraphics();
g.drawImage(img, 0, 0, w, h, 0, h, w, 0, null);
g.dispose();
return dimg;
}
private File getImageFileFromSVGImage(SVGImage image) {
String filename = image.getAttributeValue("href", SVGConstants.XLINK_NS);
File testFile = new File(filename);
return (testFile.isAbsolute() ? testFile : new File(input.getFile().getParentFile().getAbsolutePath() + "/" + filename));
}
private void replaceTextImagesWithText() {
if (rawPrimitives.getImageList().size() == 0) {
return;
}
Set<Complex> done = new HashSet<Complex>();
OCRManager manager = new OCRManager();
for (SVGImage image : rawPrimitives.getImageList()) {
try {
checkTime("Took too long to convert images to text");
image.applyTransformAttributeAndRemove();
if (image.getWidth() > parameters.getMaximumImageElementWidthForOCR()) {
continue;
}
File file = getImageFileFromSVGImage(image);
BufferedImage bufferedImage = flipHorizontally(ImageIO.read(file));
/*Tesseract tess = Tesseract.getInstance();
try {
s = tess.doOCR(im);
} catch (TesseractException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
SVGText text = manager.scan(bufferedImage, new Real2Range(new RealRange(image.getX(), image.getX() + image.getWidth()), new RealRange(Math.min(image.getY(), image.getY() + image.getHeight()), Math.max(image.getY(), image.getY() + image.getHeight()))), parameters.getBlackThreshold(), parameters.getMaximumOCRError());
if (text != null) {
image.getParent().replaceChild(image, text);
//text.copyAttributesFrom(image);
derivedPrimitives.getTextList().add(text);
derivedPrimitives.getImageList().remove(image);
}
if (!done.add(new Complex(image.getX(), image.getY())) || bufferedImage.getWidth() < parameters.getMimimumImageWidthForOCR()) {
derivedPrimitives.getImageList().remove(image);
continue;
}
} catch (IOException e) {
System.err.println("Error handling image within SVG file - it's probably embedded in base 64, but it should be linked to and stored separately");
e.printStackTrace();
} catch (Exception e) {
//TODO handle other images
}
}
manager.handleAmbiguousTexts(parameters.getTextCoordinateTolerance(), parameters.getAllowedFontSizeVariation());
}
/*private void convertImagesOfTextToText() {
for (SVGImage image : rawPrimitives.getImageList()) {
String path = image.getAttributeValue("href", "xlink");
}
}*/
/*private void createWords() {
TextStructurer t = new TextStructurer(derivedPrimitives.getTextList());
//List<RawWords> lines = t.createRawWordsList();
List<ScriptLine> lines = t.getScriptedLineList();
//j.get(0).getScriptWordList().get(0).createSuscriptTextLineList();
List<JoinableScriptWord> words = new ArrayList<JoinableScriptWord>();
higherPrimitives.setWordsList(words);
for (ScriptLine line : lines) {
for (ScriptWord word : line.getScriptWordList()) {
words.add(new JoinableScriptWord(word));
}
}
}*/
private void handleShortLines() {
List<HatchedBond> hatchList = new ArrayList<HatchedBond>();
higherPrimitives.setHatchedBondList(hatchList);
List<SVGLine> smallLines = new ArrayList<SVGLine>();
for (SVGLine l : derivedPrimitives.getLineList()) {
if (l.getXY(0).getDistance(l.getXY(1)) < parameters.getHatchLineMaximumLength() && l.getXY(0).getDistance(l.getXY(1)) > 0) {//TODO l.getLength() < hatchLineMaximumLength) {
smallLines.add(l);
}
}
higherPrimitives.setChargeList(new ArrayList<Charge>());
if (smallLines.size() == 0) {
mutuallyExclusiveShortLineTriples = new ArrayList<MutuallyExclusiveShortLineTriple>();
mutuallyExclusiveShortLinePairTriples = new ArrayList<MutuallyExclusiveShortLinePairTriple>();
return;
}
UnionFind<SVGLine> hatchedBonds = UnionFind.create(smallLines);
for (int i = 0; i < smallLines.size(); i++) {
SVGLine firstLine = smallLines.get(i);
for (int j = i + 1; j < smallLines.size(); j++) {
checkTime("Took too long to handle short lines");
SVGLine secondLine = smallLines.get(j);
Double dist = firstLine.calculateUnsignedDistanceBetweenLines(secondLine, new Angle((firstLine.getLength() < parameters.getTinyHatchLineMaximumLength() || secondLine.getLength() < parameters.getTinyHatchLineMaximumLength() ? parameters.getMaximumAngleForParallelIfOneLineIsTiny() : parameters.getMaximumAngleForParallel()), Units.RADIANS));
if (dist != null && dist < parameters.getHatchLinesMaximumSpacing() && dist > parameters.getHatchLinesMinimumSpacing() && (firstLine.overlapsWithLine(secondLine, parameters.getLineOverlapEpsilon()) || secondLine.overlapsWithLine(firstLine, parameters.getLineOverlapEpsilon()))) {
try {
hatchedBonds.union(firstLine, secondLine);
} catch (IllegalArgumentException e) {
}
}
if ((firstLine.isHorizontal(parameters.getFlatLineEpsilon()) || secondLine.isHorizontal(parameters.getFlatLineEpsilon())) && firstLine.overlapsWithLine(secondLine, parameters.getLineOverlapEpsilon()) && secondLine.overlapsWithLine(firstLine, parameters.getLineOverlapEpsilon()) && firstLine.getEuclidLine().isPerpendicularTo(secondLine.getEuclidLine(), new Angle(parameters.getPlusChargeAngleTolerance(), Units.DEGREES))) {
hatchedBonds.remove(firstLine);
hatchedBonds.remove(secondLine);
higherPrimitives.getLineList().remove(firstLine);
higherPrimitives.getLineList().remove(secondLine);
higherPrimitives.getLineChargeList().add(new Charge(parameters, firstLine, secondLine));
}
}
}
handleShortLines(hatchedBonds);
}
private void handleShortLines(UnionFind<SVGLine> disjointSets) {
final double threshold = parameters.getThresholdForOrderingCheckForHatchedBonds();
mutuallyExclusiveShortLineTriples = new ArrayList<MutuallyExclusiveShortLineTriple>();
mutuallyExclusiveShortLinePairTriples = new ArrayList<MutuallyExclusiveShortLinePairTriple>();
List<HatchedBond> hatchList = higherPrimitives.getHatchedBondList();
set: for (Set<SVGLine> set : disjointSets.snapshot()) {
ArrayList<SVGLine> lines1 = new ArrayList<SVGLine>(set);
ArrayList<SVGLine> lines2 = new ArrayList<SVGLine>(set);
Collections.sort(lines1, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 firstOfI = (i.getXY(0).getX() < i.getXY(1).getX() ? i.getXY(0) : i.getXY(1));
Real2 firstOfJ = (j.getXY(0).getX() < j.getXY(1).getX() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(firstOfI.getX(), firstOfJ.getX(), threshold) ? Double.compare(firstOfI.getY(), firstOfJ.getY()) : Double.compare(firstOfI.getX(), firstOfJ.getX()));
}});
Collections.sort(lines2, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 firstOfI = (i.getXY(0).getY() < i.getXY(1).getY() ? i.getXY(0) : i.getXY(1));
Real2 firstOfJ = (j.getXY(0).getY() < j.getXY(1).getY() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(firstOfI.getY(), firstOfJ.getY(), threshold) ? Double.compare(firstOfI.getX(), firstOfJ.getX()) : Double.compare(firstOfI.getY(), firstOfJ.getY()));
}});
ArrayList<SVGLine> lines3 = (ArrayList<SVGLine>) lines1.clone();
Collections.reverse(lines3);
ArrayList<SVGLine> lines4 = (ArrayList<SVGLine>) lines1.clone();
ArrayList<SVGLine> lines5 = (ArrayList<SVGLine>) lines1.clone();
Collections.sort(lines4, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 secondOfI = (i.getXY(0).getX() >= i.getXY(1).getX() ? i.getXY(0) : i.getXY(1));
Real2 secondOfJ = (j.getXY(0).getX() >= j.getXY(1).getX() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(secondOfI.getX(), secondOfJ.getX(), threshold) ? Double.compare(secondOfI.getY(), secondOfJ.getY()) : Double.compare(secondOfI.getX(), secondOfJ.getX()));
}});
Collections.sort(lines5, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 secondOfI = (i.getXY(0).getY() >= i.getXY(1).getY() ? i.getXY(0) : i.getXY(1));
Real2 secondOfJ = (j.getXY(0).getY() >= j.getXY(1).getY() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(secondOfI.getY(), secondOfJ.getY(), threshold) ? Double.compare(secondOfI.getX(), secondOfJ.getX()) : Double.compare(secondOfI.getY(), secondOfJ.getY()));
}});
ArrayList<SVGLine> lines6 = (ArrayList<SVGLine>) lines4.clone();
Collections.reverse(lines6);
ArrayList<SVGLine> lines7 = (ArrayList<SVGLine>) lines1.clone();
ArrayList<SVGLine> lines8 = (ArrayList<SVGLine>) lines1.clone();
Collections.sort(lines7, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
return (Real.isEqual(i.getMidPoint().getX(), j.getMidPoint().getX(), threshold) ? Double.compare(i.getMidPoint().getY(), j.getMidPoint().getY()) : Double.compare(i.getMidPoint().getX(), j.getMidPoint().getX()));
}});
Collections.sort(lines8, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
return (Real.isEqual(i.getMidPoint().getY(), j.getMidPoint().getY(), threshold) ? Double.compare(i.getMidPoint().getX(), j.getMidPoint().getX()) : Double.compare(i.getMidPoint().getY(), j.getMidPoint().getY()));
}});
ArrayList<SVGLine> lines9 = (ArrayList<SVGLine>) lines7.clone();
Collections.reverse(lines9);
boolean firstEndPointsAndSecondEndPointsOrdered = ((lines1.equals(lines2) || lines3.equals(lines2)) && (lines4.equals(lines5) || lines6.equals(lines5)));
boolean firstEndPointsAndMidPointsOrdered = ((lines1.equals(lines2) || lines3.equals(lines2)) && (lines7.equals(lines8) || lines9.equals(lines8)));
boolean secondEndPointsAndMidPointsOrdered = ((lines4.equals(lines5) || lines6.equals(lines5)) && (lines7.equals(lines8) || lines9.equals(lines8)));
if (firstEndPointsAndSecondEndPointsOrdered || firstEndPointsAndMidPointsOrdered || secondEndPointsAndMidPointsOrdered) {
ArrayList<SVGLine> lines;
if (firstEndPointsAndSecondEndPointsOrdered || firstEndPointsAndMidPointsOrdered) {
lines = lines1;
} else {
lines = lines4;
}
try {
double change = lines.get(1).getLength() - lines.get(0).getLength();
double direction = Math.signum(change);
double firstLength = lines.get(0).getLength();
for (int i = 2; i < lines.size() && change > parameters.getLengthTolerance(); i++) {
if (Math.signum(lines.get(i).getLength() - firstLength) != direction) {
continue set;
}
}
} catch (IndexOutOfBoundsException e) {
}
HatchedBond hatchedBond = new HatchedBond(parameters, lines);
hatchList.add(hatchedBond);
if (lines.size() > 2) {
higherPrimitives.getLineList().removeAll(lines);
} else if (lines.size() == 2) {
mutuallyExclusiveShortLinePairTriples.add(new MutuallyExclusiveShortLinePairTriple(hatchedBond, lines.get(0), lines.get(1)));
} else {
Charge charge = null;
if (lines.get(0).isHorizontal(parameters.getFlatLineEpsilon()) && !lines.get(0).isVertical(parameters.getFlatLineEpsilon())) {
charge = new Charge(parameters, lines);
higherPrimitives.getLineChargeList().add(charge);
}
mutuallyExclusiveShortLineTriples.add(new MutuallyExclusiveShortLineTriple(hatchedBond, charge, lines.get(0)));
}
}
}
}
private void createJunctions() {
createJoinableList();
List<Joinable> joinables = higherPrimitives.getJoinableList();
List<JoinPoint> joinPoints = extractAtomLabelsAndGetRemainingJoinPoints(joinables);
UnionFind<JoinPoint> joinPointsGroupedIntoJunctions = UnionFind.create(joinPoints);
//int deleted = 0;
attemptToJoinListOfJoinables(joinables, joinPointsGroupedIntoJunctions);
try {
handleAmbiguities(joinPointsGroupedIntoJunctions);
} catch (IllegalArgumentException e) {
joinPoints.clear();
LOG.debug("Processing failed as the diagram was too complex");
}
List<Junction> junctions = new ArrayList<Junction>();
if (joinPoints.size() != 0) {
for (Set<JoinPoint> junctionJoinPoints : joinPointsGroupedIntoJunctions.snapshot()) {
//if (junctionJoinPoints.size() != 1) {
/*Set<Joinable> junctionJoinables = new HashSet<Joinable>();
Set<JoinPoint> newJunctionJoinPoints = new HashSet <JoinPoint>();
for (JoinPoint point : junctionJoinPoints) {
if (junctionJoinables.add(point.getJoinable())) {
newJunctionJoinPoints.add(point);
} else {
newJunctionJoinPoints.removeAll(point.getJoinable().getJoinPoints());
removeJoinable(point.getJoinable());
//junctionJoinables.remove(point.getJoinable());
}
}
for (Joinable j1 : junctionJoinables) {
int numberParallel = 0;
for (Joinable j2 : junctionJoinables) {
if (Joinable.areParallel(j1, j2)) {
numberParallel++;
if (numberParallel == 3) {
for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}
continue junction;
}
}
}
}
junctions.add(new Junction(newJunctionJoinPoints));*/
//}
junctions.add(new Junction(junctionJoinPoints));
}
}
higherPrimitives.setJunctionList(junctions);
/*JoinPoint commonPoint = joinablei.getIntersectionPoint(joinablej);
if (commonPoint != null) {
Junction junction = new Junction(joinablei, joinablej, commonPoint);
rawJunctionList.add(junction);
String junctAttVal = "junct"+"."+rawJunctionList.size();
junction.addAttribute(new Attribute(SVGElement.ID, junctAttVal));
if (junction.getCoordinates() == null && commonPoint.getPoint() != null) {
junction.setCoordinates(commonPoint.getPoint());
}
LOG.debug("junct: "+junction.getId()+" between " + joinablei.getClass() + " and " + joinablej.getClass() + " with coords "+junction.getCoordinates()+" "+commonPoint.getPoint());
}
}
}*/
/*createRawJunctionList();
List<Junction> junctionList = new ArrayList<Junction>(higherPrimitives.getRawJunctionList());
for (int i = junctionList.size() - 1; i > 0; i--) {
Junction labile = junctionList.get(i);
for (int j = 0; j < i; j++) {
Junction fixed = junctionList.get(j);
if (fixed.containsCommonPoints(labile)) {
labile.transferDetailsTo(fixed);
junctionList.remove(i);
break;
}
}
}
higherPrimitives.setMergedJunctionList(junctionList);*/
}
private void attemptToJoinListOfJoinables(List<Joinable> joinables, UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
List<JoinableText> texts = new ArrayList<JoinableText>();
for (int i = 0; i < joinables.size() - 1; i++) {
Joinable joinableI = joinables.get(i);
if (!(joinableI instanceof JoinableText)) {
for (int j = i + 1; j < joinables.size(); j++) {
Joinable joinableJ = joinables.get(j);
if (!(joinableJ instanceof JoinableText)) {
checkTime("Took too long to determine what is joined to what");
//System.out.println(joinableI + "\n" + joinableJ);
joinPointsGroupedIntoJunctions.unionAll(getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, joinableI, joinableJ));
}
}
} else {
texts.add((JoinableText) joinableI);
}
}
if (joinables.size() > 0) {
if (joinables.get(joinables.size() - 1) instanceof JoinableText) {
texts.add((JoinableText) joinables.get(joinables.size() - 1));
}
attemptToJoinTexts(texts, joinables, joinPointsGroupedIntoJunctions);
}
}
private void attemptToJoinTexts(List<JoinableText> texts, List<Joinable> joinables, UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
for (int i = 0; i < texts.size() - 1; i++) {
JoinableText textI = texts.get(i);
for (int j = i + 1; j < texts.size(); j++) {
JoinableText textJ = texts.get(j);
checkTime("Took too long to determine what is joined to what");
joinPointsGroupedIntoJunctions.unionAll(getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, textI, textJ));
}
}
for (JoinableText text : texts) {
Set<JoinPoint> joinPoints = new HashSet<JoinPoint>();
for (Joinable joinable : joinables) {
if (!(joinable instanceof JoinableText)) {
checkTime("Took too long to determine what is joined to what");
List<JoinPoint> overlap = getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, text, joinable);
joinPoints.addAll(overlap);
for (JoinPoint j : overlap) {
if (!(j.getJoinable() instanceof JoinableText)) {
joinPoints.addAll(joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(j));
}
}
}
}
List<JoinPoint> actualJoinPoints = new ArrayList<JoinPoint>();
i: for (JoinPoint joinPointI : joinPoints) {
for (JoinPoint joinPointJ : joinPoints) {
if (joinPointI != joinPointJ && joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(joinPointI).contains(joinPointJ)) {
continue i;
}
}
actualJoinPoints.add(joinPointI);
}
joinPointsGroupedIntoJunctions.unionAll(actualJoinPoints);
}
}
private List<JoinPoint> getListOfOverlappingJoinPointsForJoinables(UnionFind<JoinPoint> joinPointsGroupedIntoJunctions, Joinable joinableI, Joinable joinableJ) {
Set<JoinPoint> overlapSet = joinableI.overlapWith(joinableJ);
if (overlapSet != null) {
List<JoinPoint> overlapList = new ArrayList<JoinPoint>(overlapSet);
if (!joinPointsGroupedIntoJunctions.contains(overlapList.get(0)) || !joinPointsGroupedIntoJunctions.contains(overlapList.get(1)) || (overlapList.size() > 2 && !joinPointsGroupedIntoJunctions.contains(overlapList.get(2))) || (overlapList.size() > 3 && !joinPointsGroupedIntoJunctions.contains(overlapList.get(3)))) {
return new ArrayList<JoinPoint>();
}
if (mutuallyExclusive(joinableI, joinableJ)) {
return new ArrayList<JoinPoint>();
}
if (joinableI instanceof JoinableText && joinableJ instanceof JoinableText) {
if (JoinableText.doTextsJoin((JoinableText) joinableI, (JoinableText) joinableJ, parameters)) {
//joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));
return overlapList;
}
} else if ((joinableI instanceof JoinableText && joinableJ.getJoinPoints().size() == 2) || (joinableJ instanceof JoinableText && joinableI.getJoinPoints().size() == 2)) {
Joinable lineJoinable = (joinableI instanceof JoinableText ? joinableJ : joinableI);
JoinPoint lineJoinEnd = (overlapList.get(0).getJoinable() instanceof JoinableText ? overlapList.get(1) : overlapList.get(0));
JoinPoint lineOtherEnd = (lineJoinable.getJoinPoints().get(0) == lineJoinEnd ? lineJoinable.getJoinPoints().get(1) : lineJoinable.getJoinPoints().get(0));
Line2 line = new Line2(lineOtherEnd.getPoint(), lineJoinEnd.getPoint());
JoinPoint text = (overlapList.get(0).getJoinable() instanceof JoinableText ? overlapList.get(0) : overlapList.get(1));
Line2 testLine = new Line2(lineJoinEnd.getPoint(), text.getPoint());
if (isNumber((SVGText) text.getJoinable().getSVGElement()) || line.isParallelTo(testLine, new Angle(parameters.getTightBondAndTextAngle(), Units.DEGREES))) {
return overlapList;
} else {
text.setRadius(text.getRadius() * parameters.getSmallRadiusExpansion() / parameters.getLargeRadiusExpansion());
Set<JoinPoint> overlapSet2 = joinableI.overlapWith(joinableJ);
text.setRadius(text.getRadius() * parameters.getLargeRadiusExpansion() / parameters.getSmallRadiusExpansion());
if (overlapSet2 != null && line.isParallelTo(testLine, new Angle(parameters.getLooseBondAndTextAngle(), Units.DEGREES))) {
return overlapList;
}
}
} else {
return overlapList;
}
/*if (joinableI instanceof JoinableText && joinableJ instanceof JoinableText) {
if (doTextsJoin(joinableI, joinableJ)) {
joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));
}
} else {
joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));*/
/*if (joinableI instanceof HatchedBond) {
joinables.remove(whichLineIsWhichSingleBond.get(mutuallyExclusivePairs.get(joinableI)));
}
if (joinableJ instanceof HatchedBond) {
joinables.remove(whichLineIsWhichSingleBond.get(mutuallyExclusivePairs.get(joinableJ)));
}
if (joinableI instanceof SingleBond) {
joinables.remove(mutuallyExclusivePairs.inverse().get(joinableI));
}
if (joinableJ instanceof SingleBond) {
joinables.remove(mutuallyExclusivePairs.inverse().get(joinableJ));
}*/
//}
/*if (joinablei instanceof JoinableScriptWord && joinablej instanceof JoinableScriptWord) {
if (!((JoinableScriptWord) joinablei).getScriptWord().toUnderscoreAndCaretString().equals("H") && !((JoinableScriptWord) joinablej).getScriptWord().toUnderscoreAndCaretString().equals("H")) {
continue;
}
}*/
}
return new ArrayList<JoinPoint>();
}
private void removeJoinable(Joinable joinable) {
higherPrimitives.getJoinableList().remove(joinable);
higherPrimitives.getDoubleBondList().remove(joinable);
higherPrimitives.getHatchedBondList().remove(joinable);
higherPrimitives.getLineChargeList().remove(joinable);
}
private void handleAmbiguities(UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
JoinPoint singleBondFirst = triple.singleBond.getJoinPoints().get(0);
JoinPoint singleBondSecond = triple.singleBond.getJoinPoints().get(1);
JoinPoint hatchedBondFirst = triple.hatchedBond.getJoinPoints().get(0);
JoinPoint hatchedBondSecond = triple.hatchedBond.getJoinPoints().get(1);
JoinPoint minus = (triple.minus == null ? null : triple.minus.getJoinPoints().get(0));
if (joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondSecond) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) > 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) > 1) {
if (minus != null) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(minus);
joinPointsGroupedIntoJunctions.explode(points);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p : points) {
if (p.getJoinable() != triple.minus) {
joinables.add(p.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
}
joinPointsGroupedIntoJunctions.remove(singleBondFirst);
joinPointsGroupedIntoJunctions.remove(singleBondSecond);
joinPointsGroupedIntoJunctions.remove(minus);
removeJoinable(triple.singleBond);
higherPrimitives.getLineList().remove(triple.line);
removeJoinable(triple.minus);
} else if (joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondSecond) == 1 && (joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) == 1 || joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) == 1) && minus != null) {
joinPointsGroupedIntoJunctions.remove(singleBondFirst);
joinPointsGroupedIntoJunctions.remove(singleBondSecond);
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
removeJoinable(triple.singleBond);
higherPrimitives.getLineList().remove(triple.line);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.hatchedBond);
} else {
if (minus != null) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(minus);
joinPointsGroupedIntoJunctions.explode(points);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p : points) {
if (p.getJoinable() != triple.minus) {
joinables.add(p.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
}
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
joinPointsGroupedIntoJunctions.remove(minus);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.minus);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.minus);
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
joinPointsGroupedIntoJunctions.remove(triple.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(triple.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(triple.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(triple.singleBond2.getJoinPoints().get(1));
removeJoinable(triple.singleBond1);
removeJoinable(triple.singleBond2);
higherPrimitives.getLineList().remove(triple.line1);
higherPrimitives.getLineList().remove(triple.line2);
if (triple.doubleBond == null) {
continue;
}
JoinPoint doubleBondFirst = triple.doubleBond.getJoinPoints().get(0);
JoinPoint doubleBondSecond = triple.doubleBond.getJoinPoints().get(1);
JoinPoint hatchedBondFirst = triple.hatchedBond.getJoinPoints().get(0);
JoinPoint hatchedBondSecond = triple.hatchedBond.getJoinPoints().get(1);
if ((joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) > 1 || joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) > 1) && joinPointsGroupedIntoJunctions.getSizeOfPartition(doubleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(doubleBondSecond) == 1) {
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(triple.doubleBond);
} else {
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
removeJoinable(triple.hatchedBond);
}
}
Set<SingleBond> singleBonds = new HashSet<SingleBond>();
for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
singleBonds.add(pair.singleBond1);
singleBonds.add(pair.singleBond2);
}
pair: for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
JoinPoint doubleBondFirst = pair.doubleBond.getJoinPoints().get(0);
JoinPoint doubleBondSecond = pair.doubleBond.getJoinPoints().get(1);
boolean sewn = joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(1)));
if (sewn) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(doubleBondFirst);
boolean foundParallel = false;
for (JoinPoint p1 : points) {
if (!(p1.getJoinable() instanceof DoubleBond) && !singleBonds.contains(p1.getJoinable()) && Joinable.areParallel(p1.getJoinable(), pair.doubleBond, new Angle(parameters.getToleranceForParallelJoinables(), Units.RADIANS))) {
if (foundParallel) {
joinPointsGroupedIntoJunctions.explode(points);
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(pair.doubleBond);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p2 : points) {
if (p2.getJoinable() != pair.doubleBond) {
joinables.add(p2.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
/*for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}*/
continue pair;
} else {
foundParallel = true;
}
}
}
points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(doubleBondSecond);
foundParallel = false;
for (JoinPoint p1 : points) {
if (!(p1.getJoinable() instanceof DoubleBond) && !singleBonds.contains(p1.getJoinable()) && Joinable.areParallel(p1.getJoinable(), pair.doubleBond, new Angle(parameters.getToleranceForParallelJoinables(), Units.RADIANS))) {
if (foundParallel) {
joinPointsGroupedIntoJunctions.explode(points);
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(pair.doubleBond);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p2 : points) {
if (p2.getJoinable() != pair.doubleBond) {
joinables.add(p2.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
/*for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}*/
continue pair;
} else {
foundParallel = true;
}
}
}
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(1));
higherPrimitives.getLineList().remove(pair.line1);
higherPrimitives.getLineList().remove(pair.line2);
removeJoinable(pair.singleBond1);
removeJoinable(pair.singleBond2);
} else {
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(1));
higherPrimitives.getLineList().remove(pair.line1);
higherPrimitives.getLineList().remove(pair.line2);
removeJoinable(pair.singleBond1);
removeJoinable(pair.singleBond2);
}
}
}
private boolean mutuallyExclusive(Joinable joinableI, Joinable joinableJ) {
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
if (joinableI == triple.hatchedBond && joinableJ == triple.minus || joinableJ == triple.hatchedBond && joinableI == triple.minus) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond || joinableJ == triple.hatchedBond && joinableI == triple.singleBond) {
return true;
}
if (joinableI == triple.singleBond && joinableJ == triple.minus || joinableJ == triple.singleBond && joinableI == triple.minus) {
return true;
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
if (joinableI == triple.hatchedBond && joinableJ == triple.doubleBond || joinableJ == triple.hatchedBond && joinableI == triple.doubleBond) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond1 || joinableJ == triple.hatchedBond && joinableI == triple.singleBond1) {
return true;
}
if (joinableI == triple.singleBond1 && joinableJ == triple.doubleBond || joinableJ == triple.singleBond1 && joinableI == triple.doubleBond) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond2 || joinableJ == triple.hatchedBond && joinableI == triple.singleBond2) {
return true;
}
if (joinableI == triple.doubleBond && joinableJ == triple.singleBond2 || joinableJ == triple.doubleBond && joinableI == triple.singleBond2) {
return true;
}
if (joinableI == triple.singleBond1 && joinableJ == triple.singleBond2 || joinableJ == triple.singleBond1 && joinableI == triple.singleBond2) {
return true;
}
}
/*for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
if (joinableI == pair.singleBond2 && joinableJ == pair.doubleBond || joinableJ == pair.singleBond2 && joinableI == pair.doubleBond) {
return true;
}
if (joinableI == pair.singleBond2 && joinableJ == pair.singleBond1 || joinableJ == pair.singleBond2 && joinableI == pair.singleBond1) {
return true;
}
if (joinableI == pair.singleBond1 && joinableJ == pair.doubleBond || joinableJ == pair.singleBond1 && joinableI == pair.doubleBond) {
return true;
}
}*/
return false;
}
private List<JoinPoint> extractAtomLabelsAndGetRemainingJoinPoints(List<Joinable> joinables) {
List<JoinPoint> remainingJoinPoints = new ArrayList<JoinPoint>();
Map<Double, List<JoinableText>> listsOfTextsByFontSize = new LinkedHashMap<Double, List<JoinableText>>();
for (Joinable j : joinables) {
if (j instanceof JoinableText) {// && isLabel(((JoinableText) j).getSVGElement())) {// && !"1".equals(((JoinableText) j).getSVGElement().getText()) && !"2".equals(((JoinableText) j).getSVGElement().getText()) && !"3".equals(((JoinableText) j).getSVGElement().getText()) && !"4".equals(((JoinableText) j).getSVGElement().getText())) {
List<JoinableText> joinablesForSize = listsOfTextsByFontSize.get(((JoinableText) j).getSVGElement().getFontSize());
if (joinablesForSize == null) {
joinablesForSize = new ArrayList<JoinableText>();
listsOfTextsByFontSize.put(((JoinableText) j).getSVGElement().getFontSize(), joinablesForSize);
}
joinablesForSize.add((JoinableText) j);
} else {
remainingJoinPoints.addAll(j.getJoinPoints());
}
}
double fontSizeOfLabels = Double.MAX_VALUE;
list: for (Entry<Double, List<JoinableText>> list : listsOfTextsByFontSize.entrySet()) {
AreInSameStringDetector sameString = new AreInSameStringDetector(list.getValue(), parameters, false, true);
ImmutableCollection<Set<Joinable>> groups = sameString.texts.snapshot();
//List<Integer> labelNumbers = new ArrayList<Integer>();
Map<Real2Range, Integer> labelNumbers = new LinkedHashMap<Real2Range, Integer>();
group: for (Set<Joinable> group : groups) {
List<Joinable> potentialLabelTexts = new ArrayList<Joinable>(group);
Joinable.sortJoinablesByX(potentialLabelTexts);
String number = "";
Real2Range bounds = new Real2Range();
for (Joinable potentialLabelText : potentialLabelTexts) {
if (!isLabel((SVGText) potentialLabelText.getSVGElement())) {
for (Joinable t : group) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
continue group;
}
bounds.add(potentialLabelText.getJoinPoints().get(0).getPoint());
if (isNumber((SVGText) potentialLabelText.getSVGElement())) {
number += ((SVGText) potentialLabelText.getSVGElement()).getText();
}
}
try {
labelNumbers.put(bounds, Integer.parseInt(number));
} catch (NumberFormatException e) {
}
}
List<Integer> labelNumbersToBeSorted = new ArrayList<Integer>(labelNumbers.values());
Collections.sort(labelNumbersToBeSorted);
int previousPreviousLabel = 0;
int previousLabel = 0;
for (Integer i : labelNumbersToBeSorted) {
if (i - previousLabel > labelNumbersToBeSorted.get(labelNumbersToBeSorted.size() - 1) * parameters.getMaximumLabelSequenceGap()) {
for (JoinableText t : list.getValue()) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
continue list;
}
previousPreviousLabel = previousLabel;
previousLabel = i;
}
if (list.getKey() < fontSizeOfLabels && labelNumbers.size() > 1) {
if (atomLabelTexts != null) {
for (JoinableText t : atomLabelTexts) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
}
atomLabelTexts = list.getValue();
atomLabelPositionsAndNumbers = labelNumbers;
fontSizeOfLabels = list.getKey();
} else {
for (JoinableText t : list.getValue()) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
}
}
if (atomLabelTexts == null) {
atomLabelTexts = new ArrayList<JoinableText>();
atomLabelPositionsAndNumbers = new HashMap<Real2Range, Integer>();
}
return remainingJoinPoints;
}
private boolean isLetter(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[A-Za-z]"));
}
private boolean isNumber(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[0-9]"));
}
private boolean isLabel(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[0-9'a]"));
}
protected void createJoinableList() {
List<Joinable> joinableList = createJoinableList(higherPrimitives.getLineList());
joinableList.addAll(createJoinableList(derivedPrimitives.getPolygonList()));
joinableList.addAll(createJoinableList(derivedPrimitives.getPathList()));
joinableList.addAll(higherPrimitives.getDoubleBondList());
joinableList.addAll(higherPrimitives.getHatchedBondList());
joinableList.addAll(higherPrimitives.getLineChargeList());
//joinableList.addAll(higherPrimitives.getWordList());
joinableList.addAll(createJoinableList(derivedPrimitives.getTextList()));
//joinableList.addAll(createJoinableList(derivedPrimitives.getImageList()));
higherPrimitives.addJoinableList(joinableList);
}
public List<Joinable> createJoinableList(List<? extends SVGElement> elementList) {
List<Joinable> joinableList = new ArrayList<Joinable>();
for (SVGElement element : elementList) {
Joinable joinable = createJoinable(element);
if (joinable != null) {
joinableList.add(joinable);
}
}
return joinableList;
}
private Joinable createJoinable(SVGElement element) {
Joinable joinable = null;
if (element instanceof SVGLine) {
joinable = new SingleBond(parameters, (SVGLine) element);
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
if (triple.line == element) {
triple.singleBond = (SingleBond) joinable;
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
if (triple.line1 == element) {
triple.singleBond1 = (SingleBond) joinable;
}
if (triple.line2 == element) {
triple.singleBond2 = (SingleBond) joinable;
}
}
for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
if (pair.line1 == element) {
pair.singleBond1 = (SingleBond) joinable;
}
if (pair.line2 == element) {
pair.singleBond2 = (SingleBond) joinable;
}
}
} else if (element instanceof SVGText) {
if (("+".equals(((SVGText) element).getText()) || "-".equals(((SVGText) element).getText())) && !JoinableText.anyTextsInSameString((SVGText) element, derivedPrimitives.getTextList(), parameters, false, true) && !JoinableText.anyTextsToRightInSameString((SVGText) element, derivedPrimitives.getTextList(), parameters, true)) {
joinable = new Charge(parameters, (SVGText) element);
} else {
joinable = new JoinableText(parameters, (SVGText) element);
}
} else if (element instanceof SVGPolygon && ((SVGPolygon) element).createLineList(true).size() == 3) {
double shortest = Double.MAX_VALUE;
for (SVGLine line : ((SVGPolygon) element).getLineList()) {
if (line.getLength() < shortest) {
shortest = line.getLength();
}
}
if (shortest > 0.5) {
joinable = new WedgeBond(parameters, (SVGPolygon) element);
wedgeBonds.add((WedgeBond) joinable);
}
} else if (element instanceof SVGPolygon && ((SVGPolygon) element).createLineList(true).size() == 4) {
for (int i = 0; i < ((SVGPolygon) element).getReal2Array().size(); i++) {
Real2Array withoutPoint = new Real2Array(((SVGPolygon) element).getReal2Array());
Real2 deleted = withoutPoint.get(i);
withoutPoint.deleteElement(i);
SVGPolygon newPoly = new SVGPolygon(withoutPoint);
if (newPoly.containsPoint(deleted, 0)) {//withoutPoint.getRange2().includes(((SVGPolygon) element).getReal2Array().get(i))) {
((SVGPolygon) element).setReal2Array(withoutPoint);
joinable = new WedgeBond(parameters, (SVGPolygon) element);
wedgeBonds.add((WedgeBond) joinable);
break;
}
}
} else if (element instanceof SVGPath) {
try {
joinable = new WigglyBond(parameters, (SVGPath) element);
} catch (IllegalArgumentException e) {
}
}
if (joinable == null) {
LOG.debug("Unknown joinable: " + element);
}
return joinable;
}
private void createDoubleBondList() {
DoubleBondManager doubleBondManager = new DoubleBondManager(parameters);
List<DoubleBond> doubleBondList;
try {
doubleBondList = doubleBondManager.createDoubleBondListWithoutReusingLines(higherPrimitives.getLineList(), startTime + timeout - System.currentTimeMillis());
} catch (TimeoutException e) {
throw new UncheckedTimeoutException(e.getMessage());
}
//doubleBondManager.removeUsedDoubleBondPrimitives(higherPrimitives.getLineList());
higherPrimitives.setDoubleBondList(doubleBondList);
mutuallyExclusiveLinePairPairs = new ArrayList<ChemistryBuilder.MutuallyExclusiveLinePairPair>();
bond: for (DoubleBond bond : doubleBondList) {
for (MutuallyExclusiveShortLinePairTriple pair : mutuallyExclusiveShortLinePairTriples) {
if ((pair.line1 == bond.getLine(0) && pair.line2 == bond.getLine(1)) || (pair.line1 == bond.getLine(1) && pair.line2 == bond.getLine(0))) {
pair.doubleBond = bond;
continue bond;
}
}
mutuallyExclusiveLinePairPairs.add(new MutuallyExclusiveLinePairPair(bond));
//higherPrimitives.getLineList().add(bond.getLine(0));
//higherPrimitives.getLineList().add(bond.getLine(1));
}
}
/*private void createRawJunctionList() {
createJoinableList();
List<Joinable> joinableList = higherPrimitives.getJoinableList();
List<Junction> rawJunctionList = new ArrayList<Junction>();
for (int i = 0; i < joinableList.size() - 1; i++) {
Joinable joinablei = joinableList.get(i);
for (int j = i + 1; j < joinableList.size(); j++) {
Joinable joinablej = joinableList.get(j);
JoinPoint commonPoint = joinablei.getIntersectionPoint(joinablej);
if (commonPoint != null) {
Junction junction = new Junction(joinablei, joinablej, commonPoint);
rawJunctionList.add(junction);
String junctAttVal = "junct"+"."+rawJunctionList.size();
junction.addAttribute(new Attribute(SVGElement.ID, junctAttVal));
if (junction.getCoordinates() == null && commonPoint.getPoint() != null) {
junction.setCoordinates(commonPoint.getPoint());
}
LOG.debug("junct: "+junction.getId()+" between " + joinablei.getClass() + " and " + joinablej.getClass() + " with coords "+junction.getCoordinates()+" "+commonPoint.getPoint());
}
}
}
higherPrimitives.setRawJunctionList(rawJunctionList);
}*/
public SVGElement getSVGRoot() {
return svgRoot;
}
public HigherPrimitives getHigherPrimitives() {
return higherPrimitives;
}
public Map<Real2Range, Integer> getAtomLabels() {
return atomLabelPositionsAndNumbers;
}
void draw() {
draw(new File("target/chem/andy.svg"));
}
public void draw(File file) {
SVGG out = drawPrimitivesJoinPointsAndJunctions();
SVGSVG.wrapAndWriteAsSVG(out, file);
}
SVGG drawPrimitivesJoinPointsAndJunctions() {
SVGG out = new SVGG();
SVGG circles = new SVGG();
out.appendChild(circles);
if (higherPrimitives.getJunctionList() != null) {
for (Junction j : higherPrimitives.getJunctionList()) {
Real2 coords = (j.getCoordinates() == null ? new Real2(0, 0) : j.getCoordinates());
SVGCircle c = new SVGCircle(coords, 1.2);
c.setFill("#555555");
c.setOpacity(0.7);
c.setStrokeWidth(0.0);
circles.appendChild(c);
SVGText t = new SVGText(coords.plus(new Real2(1.5, Math.random() * 6)), j.getID());
circles.appendChild(t);
for (JoinPoint point : j.getJoinPoints()) {
SVGLine line = new SVGLine(coords, point.getPoint());
line.setStrokeWidth(0.05);
circles.appendChild(line);
}
}
}
for (SVGText t : getDerivedPrimitives().getTextList()) {
SVGText o = (SVGText) t.copy();
out.appendChild(o);
}
for (SVGLine l : getDerivedPrimitives().getLineList()) {
SVGLine o = (SVGLine) l.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (SVGPolygon p : getDerivedPrimitives().getPolygonList()) {
SVGPolygon o = (SVGPolygon) p.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (SVGPath p : getDerivedPrimitives().getPathList()) {
SVGPath o = (SVGPath) p.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (Charge t : getHigherPrimitives().getLineChargeList()) {
if (t.getSVGElement() != null) {
SVGElement e = (SVGElement) t.getSVGElement().copy();
out.appendChild(e);
}
}
/*for (SVGImage t : simpleBuilder.getDerivedPrimitives().getImageList()) {
SVGText e = new SVGText
out.appendChild(e);
}*/
if (getHigherPrimitives().getJoinableList() != null) {
for (Joinable j : getHigherPrimitives().getJoinableList()) {
for (JoinPoint p : j.getJoinPoints()) {
Real2 coords = (p.getPoint() == null ? new Real2(0, 0) : p.getPoint());
SVGCircle c = new SVGCircle(coords, p.getRadius());
if (j instanceof SingleBond) {
c.setFill("#9999FF");
} else if (j instanceof DoubleBond) {
c.setFill("#99FF99");
} else if (j instanceof HatchedBond) {
c.setFill("#FF9999");
} else if (j instanceof WedgeBond) {
c.setFill("#99FFFF");
} else if (j instanceof Charge) {
c.setFill("#FFFF99");
} else if (j instanceof JoinableText) {
c.setFill("#FF99FF");
} else if (j instanceof WigglyBond) {
c.setFill("#999999");
}
c.setOpacity(0.7);
c.setStrokeWidth(0.0);
circles.appendChild(c);
//SVGText t = new SVGText(coords.plus(new Real2(1.5, Math.random() * 6)), j.getId());
//out.appendChild(t);
}
}
}
return out;
}
} | src/main/java/org/xmlcml/ami2/chem/ChemistryBuilder.java | package org.xmlcml.ami2.chem;
import java.awt.Graphics2D;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import javax.imageio.ImageIO;
import nu.xom.Nodes;
import org.apache.commons.math.complex.Complex;
import org.apache.log4j.Logger;
import org.xmlcml.ami2.chem.Joinable.JoinPoint;
import org.xmlcml.ami2.chem.JoinableText.AreInSameStringDetector;
import org.xmlcml.ami2.chem.svg.SVGContainerNew;
import org.xmlcml.diagrams.OCRManager;
import org.xmlcml.euclid.Angle;
import org.xmlcml.euclid.Angle.Units;
import org.xmlcml.euclid.Line2;
import org.xmlcml.euclid.Real;
import org.xmlcml.euclid.Real2;
import org.xmlcml.euclid.Real2Array;
import org.xmlcml.euclid.Real2Range;
import org.xmlcml.euclid.RealRange;
import org.xmlcml.graphics.svg.SVGCircle;
import org.xmlcml.graphics.svg.SVGConstants;
import org.xmlcml.graphics.svg.SVGElement;
import org.xmlcml.graphics.svg.SVGG;
import org.xmlcml.graphics.svg.SVGImage;
import org.xmlcml.graphics.svg.SVGLine;
import org.xmlcml.graphics.svg.SVGPath;
import org.xmlcml.graphics.svg.SVGPolygon;
import org.xmlcml.graphics.svg.SVGSVG;
import org.xmlcml.graphics.svg.SVGTSpan;
import org.xmlcml.graphics.svg.SVGText;
import org.xmlcml.svgbuilder.geom.SimpleBuilder;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.UnionFind;
import com.google.common.util.concurrent.UncheckedTimeoutException;
//import net.sourceforge.tess4j.Tesseract;
//import net.sourceforge.tess4j.TesseractException;
/**
* Builds higher-level primitives from SVGPaths, SVGLines, etc. to create SVG objects
* such as TramLine and (later) Arrow.
*
* <p>SimpleBuilder's main function is to:
* <ul>
* <li>Read a raw SVG object and make lists of SVGPath and SVGText (and possibly higher levels ones
* if present).</li>
* <li>Turn SVGPaths into SVGLines , etc..</li>
* <li>Identify Junctions (line-line, line-text, and probably more).</li>
* <li>Join lines where they meet into higher level objects (TramLines, SVGRect, crosses, arrows, etc.).</li>
* <li>Create topologies (e.g. connection of lines and Junctions).</li>
* </ul>
*
* SimpleBuilder uses the services of the org.xmlcml.graphics.svg.path package and may later use
* org.xmlcml.graphics.svg.symbol.
* </p>
*
* <p>Input may either be explicit SVG primitives (e.g. <svg:rect>, <svg:line>) or
* implicit ones (<svg:path>) that can be interpreted as the above. The input may be either or
* both - we can't control it. The implicit get converted to explicit and then merged with the
* explicit:
* <pre>
* paths-> implicitLineList + rawLinelist -> explicitLineList
* </pre>
* </p>
*
* <h3>Strategy</h3>
* <p>createHigherLevelPrimitives() carries out the complete chain from svgRoot to the final
* primitives. Each step tests to see whether the result of the previous is null.
* If so it creates a non-null list and fills it if possible. </p>
*
* UPDATE: 2013-10-23 Renamed to "SimpleGeometryManager" as it doesn't deal with Words (which
* require TextStructurer). It's possible the whole higher-level primitive stuff should be removed to another
* project.
*
* @author pm286
*/
public class ChemistryBuilder extends SimpleBuilder {
private final static Logger LOG = Logger.getLogger(ChemistryBuilder.class);
private ChemistryBuilderParameters parameters = new ChemistryBuilderParameters();
protected HigherPrimitives higherPrimitives;
protected SVGContainerNew input;
//HashBiMap<HatchedBond, SVGLine> mutuallyExclusivePairs;
//Map<SVGLine, SingleBond> whichLineIsWhichSingleBond;
private List<JoinableText> atomLabelTexts;
private Map<Real2Range, Integer> atomLabelPositionsAndNumbers;
List<WedgeBond> wedgeBonds = new ArrayList<WedgeBond>();
private double scale = 1;
static class MutuallyExclusiveShortLineTriple {
HatchedBond hatchedBond;
Charge minus;
SVGLine line;
SingleBond singleBond;
public MutuallyExclusiveShortLineTriple(HatchedBond hatchedBond, Charge minus, SVGLine line) {
this.hatchedBond = hatchedBond;
this.minus = minus;
this.line = line;
}
}
static class MutuallyExclusiveShortLinePairTriple {
HatchedBond hatchedBond;
SVGLine line1;
SVGLine line2;
DoubleBond doubleBond;
SingleBond singleBond1;
SingleBond singleBond2;
public MutuallyExclusiveShortLinePairTriple(HatchedBond hatchedBond, SVGLine line1, SVGLine line2) {
this.hatchedBond = hatchedBond;
this.line1 = line1;
this.line2 = line2;
}
}
static class MutuallyExclusiveLinePairPair {
SVGLine line1;
SVGLine line2;
DoubleBond doubleBond;
SingleBond singleBond1;
SingleBond singleBond2;
public MutuallyExclusiveLinePairPair(DoubleBond doubleBond) {
this.line1 = doubleBond.getLine(0);
this.line2 = doubleBond.getLine(1);
this.doubleBond = doubleBond;
}
}
List<MutuallyExclusiveShortLineTriple> mutuallyExclusiveShortLineTriples;
List<MutuallyExclusiveShortLinePairTriple> mutuallyExclusiveShortLinePairTriples;
List<MutuallyExclusiveLinePairPair> mutuallyExclusiveLinePairPairs;
public ChemistryBuilder(SVGContainerNew svgRoot, long timeout, ChemistryBuilderParameters parameters) {
super((SVGElement) svgRoot.getElement(), timeout);
input = svgRoot;
this.parameters = parameters;
}
public ChemistryBuilder(SVGContainerNew svgRoot, ChemistryBuilderParameters parameters) {
super((SVGElement) svgRoot.getElement());
input = svgRoot;
this.parameters = parameters;
}
public ChemistryBuilder(SVGElement svgRoot, long timeout, ChemistryBuilderParameters parameters) {
super(svgRoot, timeout);
this.parameters = parameters;
}
public ChemistryBuilder(SVGElement svgRoot, ChemistryBuilderParameters parameters) {
super(svgRoot);
this.parameters = parameters;
}
public ChemistryBuilder(SVGContainerNew svgRoot, long timeout) {
super((SVGElement) svgRoot.getElement(), timeout);
input = svgRoot;
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGContainerNew svgRoot) {
super((SVGElement) svgRoot.getElement());
input = svgRoot;
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGElement svgRoot, long timeout) {
super(svgRoot, timeout);
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilder(SVGElement svgRoot) {
super(svgRoot);
parameters = new ChemistryBuilderParameters();
}
public ChemistryBuilderParameters getParameters() {
return parameters;
}
public SVGContainerNew getInputContainer() {
return input;
}
/**
* Complete processing chain for low-level SVG into high-level SVG and non-SVG primitives such as double bonds.
* <p>
* Creates junctions.
* <p>
* Runs createDerivedPrimitives().
*
* @throws TimeoutException
*/
public void createHigherPrimitives() {
if (higherPrimitives == null) {
startTiming();
createDerivedPrimitives();
replaceTextImagesWithText();
splitMultiCharacterTexts();
higherPrimitives = new HigherPrimitives();
higherPrimitives.addSingleLines(derivedPrimitives.getLineList());
handleShortLines();
createDoubleBondList();
//createWords();
createJunctions();
}
}
@Override
protected void removeNearDuplicateAndObscuredPrimitives() {
double scale = parameters.setStandardBondLengthFromSVG(derivedPrimitives.getLineList());
nearDuplicateLineRemovalDistance *= (scale / this.scale);
nearDuplicatePolygonRemovalDistance *= (scale / this.scale);
minimumCutObjectGap *= (scale / this.scale);
maximumCutObjectGap *= (scale / this.scale);
this.scale = scale;
super.removeNearDuplicateAndObscuredPrimitives();
}
private void splitMultiCharacterTexts() {
Iterator<SVGText> it = derivedPrimitives.getTextList().iterator();
List<SVGText> newTexts = new ArrayList<SVGText>();
while (it.hasNext()) {
SVGText text = it.next();
String string = text.getText();
List<SVGTSpan> spanList = new ArrayList<SVGTSpan>();
double totalWidth = 0;
if (string == null) {
Nodes spans = text.query("svg:tspan", SVGSVG.SVG_XPATH);
for (int i = 0; i < spans.size(); i++) {
SVGTSpan span = (SVGTSpan) spans.get(i);
spanList.add(span);
GlyphVector v = span.getGlyphVector();
totalWidth += v.getLogicalBounds().getWidth();
if (span.getAttributeValue("dx") != null) {
totalWidth += Double.parseDouble(span.getAttributeValue("dx"));
}
}
} else {
spanList.add(new SVGTSpan(text));
totalWidth = text.getGlyphVector().getLogicalBounds().getWidth();
}
it.remove();
double previousX = text.getX() - ("end".equals(text.getAttributeValue("text-anchor")) ? totalWidth : 0);
double previousY = text.getY();
for (SVGTSpan span : spanList) {
if (span.getX() != 0.0) {
previousX = span.getX() - ("end".equals(text.getAttributeValue("text-anchor")) ? totalWidth : 0);
}
if (span.getY() != 0.0) {
previousY = span.getY();
}
GlyphVector glyphVector = span.getGlyphVector();
String spanText = span.getText();
for (int i = 0; i < spanText.length(); i++) {
String substring = spanText.substring(i, i + 1);
SVGText newText = new SVGText(new Real2(0, 0), substring);
newTexts.add(newText);
newText.copyAttributesFrom(span);
double dX = 0;
if (span.getAttributeValue("dx") != null) {
dX = Double.parseDouble(span.getAttributeValue("dx"));
newText.removeAttribute(newText.getAttribute("dx"));
}
double dY = 0;
if (span.getAttributeValue("dy") != null) {
dY = Double.parseDouble(span.getAttributeValue("dy"));
newText.removeAttribute(newText.getAttribute("dy"));
}
newText.setX(previousX + dX + glyphVector.getGlyphPosition(i).getX());
newText.setY(previousY + dY + glyphVector.getGlyphPosition(i).getY());
}
previousX += glyphVector.getGlyphPosition(glyphVector.getNumGlyphs()).getX();
if (span.getAttributeValue("dy") != null) {
previousY += Double.parseDouble(span.getAttributeValue("dy"));
}
}
}
derivedPrimitives.getTextList().addAll(newTexts);
}
public BufferedImage flipHorizontally(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(w, h, img.getColorModel().getTransparency());
Graphics2D g = dimg.createGraphics();
g.drawImage(img, 0, 0, w, h, 0, h, w, 0, null);
g.dispose();
return dimg;
}
private File getImageFileFromSVGImage(SVGImage image) {
String filename = image.getAttributeValue("href", SVGConstants.XLINK_NS);
File testFile = new File(filename);
return (testFile.isAbsolute() ? testFile : new File(input.getFile().getParentFile().getAbsolutePath() + "/" + filename));
}
private void replaceTextImagesWithText() {
if (rawPrimitives.getImageList().size() == 0) {
return;
}
Set<Complex> done = new HashSet<Complex>();
OCRManager manager = new OCRManager();
for (SVGImage image : rawPrimitives.getImageList()) {
try {
checkTime("Took too long to convert images to text");
image.applyTransformAttributeAndRemove();
if (image.getWidth() > parameters.getMaximumImageElementWidthForOCR()) {
continue;
}
File file = getImageFileFromSVGImage(image);
BufferedImage bufferedImage = flipHorizontally(ImageIO.read(file));
/*Tesseract tess = Tesseract.getInstance();
try {
s = tess.doOCR(im);
} catch (TesseractException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
SVGText text = manager.scan(bufferedImage, new Real2Range(new RealRange(image.getX(), image.getX() + image.getWidth()), new RealRange(Math.min(image.getY(), image.getY() + image.getHeight()), Math.max(image.getY(), image.getY() + image.getHeight()))), parameters.getBlackThreshold(), parameters.getMaximumOCRError());
if (text != null) {
image.getParent().replaceChild(image, text);
//text.copyAttributesFrom(image);
derivedPrimitives.getTextList().add(text);
derivedPrimitives.getImageList().remove(image);
}
if (!done.add(new Complex(image.getX(), image.getY())) || bufferedImage.getWidth() < parameters.getMimimumImageWidthForOCR()) {
derivedPrimitives.getImageList().remove(image);
continue;
}
} catch (IOException e) {
System.err.println("Error handling image within SVG file - it's probably embedded in base 64, but it should be linked to and stored separately");
e.printStackTrace();
} catch (Exception e) {
//TODO handle other images
}
}
manager.handleAmbiguousTexts(parameters.getTextCoordinateTolerance(), parameters.getAllowedFontSizeVariation());
}
/*private void convertImagesOfTextToText() {
for (SVGImage image : rawPrimitives.getImageList()) {
String path = image.getAttributeValue("href", "xlink");
}
}*/
/*private void createWords() {
TextStructurer t = new TextStructurer(derivedPrimitives.getTextList());
//List<RawWords> lines = t.createRawWordsList();
List<ScriptLine> lines = t.getScriptedLineList();
//j.get(0).getScriptWordList().get(0).createSuscriptTextLineList();
List<JoinableScriptWord> words = new ArrayList<JoinableScriptWord>();
higherPrimitives.setWordsList(words);
for (ScriptLine line : lines) {
for (ScriptWord word : line.getScriptWordList()) {
words.add(new JoinableScriptWord(word));
}
}
}*/
private void handleShortLines() {
List<HatchedBond> hatchList = new ArrayList<HatchedBond>();
higherPrimitives.setHatchedBondList(hatchList);
List<SVGLine> smallLines = new ArrayList<SVGLine>();
for (SVGLine l : derivedPrimitives.getLineList()) {
if (l.getXY(0).getDistance(l.getXY(1)) < parameters.getHatchLineMaximumLength() && l.getXY(0).getDistance(l.getXY(1)) > 0) {//TODO l.getLength() < hatchLineMaximumLength) {
smallLines.add(l);
}
}
higherPrimitives.setChargeList(new ArrayList<Charge>());
if (smallLines.size() == 0) {
mutuallyExclusiveShortLineTriples = new ArrayList<MutuallyExclusiveShortLineTriple>();
mutuallyExclusiveShortLinePairTriples = new ArrayList<MutuallyExclusiveShortLinePairTriple>();
return;
}
UnionFind<SVGLine> hatchedBonds = UnionFind.create(smallLines);
for (int i = 0; i < smallLines.size(); i++) {
SVGLine firstLine = smallLines.get(i);
for (int j = i + 1; j < smallLines.size(); j++) {
checkTime("Took too long to handle short lines");
SVGLine secondLine = smallLines.get(j);
Double dist = firstLine.calculateUnsignedDistanceBetweenLines(secondLine, new Angle((firstLine.getLength() < parameters.getTinyHatchLineMaximumLength() || secondLine.getLength() < parameters.getTinyHatchLineMaximumLength() ? parameters.getMaximumAngleForParallelIfOneLineIsTiny() : parameters.getMaximumAngleForParallel()), Units.RADIANS));
if (dist != null && dist < parameters.getHatchLinesMaximumSpacing() && dist > parameters.getHatchLinesMinimumSpacing() && (firstLine.overlapsWithLine(secondLine, parameters.getLineOverlapEpsilon()) || secondLine.overlapsWithLine(firstLine, parameters.getLineOverlapEpsilon()))) {
try {
hatchedBonds.union(firstLine, secondLine);
} catch (IllegalArgumentException e) {
}
}
if ((firstLine.isHorizontal(parameters.getFlatLineEpsilon()) || secondLine.isHorizontal(parameters.getFlatLineEpsilon())) && firstLine.overlapsWithLine(secondLine, parameters.getLineOverlapEpsilon()) && secondLine.overlapsWithLine(firstLine, parameters.getLineOverlapEpsilon()) && firstLine.getEuclidLine().isPerpendicularTo(secondLine.getEuclidLine(), new Angle(parameters.getPlusChargeAngleTolerance(), Units.DEGREES))) {
hatchedBonds.remove(firstLine);
hatchedBonds.remove(secondLine);
higherPrimitives.getLineList().remove(firstLine);
higherPrimitives.getLineList().remove(secondLine);
higherPrimitives.getLineChargeList().add(new Charge(parameters, firstLine, secondLine));
}
}
}
handleShortLines(hatchedBonds);
}
private void handleShortLines(UnionFind<SVGLine> disjointSets) {
final double threshold = parameters.getThresholdForOrderingCheckForHatchedBonds();
mutuallyExclusiveShortLineTriples = new ArrayList<MutuallyExclusiveShortLineTriple>();
mutuallyExclusiveShortLinePairTriples = new ArrayList<MutuallyExclusiveShortLinePairTriple>();
List<HatchedBond> hatchList = higherPrimitives.getHatchedBondList();
set: for (Set<SVGLine> set : disjointSets.snapshot()) {
ArrayList<SVGLine> lines1 = new ArrayList<SVGLine>(set);
ArrayList<SVGLine> lines2 = new ArrayList<SVGLine>(set);
Collections.sort(lines1, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 firstOfI = (i.getXY(0).getX() < i.getXY(1).getX() ? i.getXY(0) : i.getXY(1));
Real2 firstOfJ = (j.getXY(0).getX() < j.getXY(1).getX() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(firstOfI.getX(), firstOfJ.getX(), threshold) ? Double.compare(firstOfI.getY(), firstOfJ.getY()) : Double.compare(firstOfI.getX(), firstOfJ.getX()));
}});
Collections.sort(lines2, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 firstOfI = (i.getXY(0).getY() < i.getXY(1).getY() ? i.getXY(0) : i.getXY(1));
Real2 firstOfJ = (j.getXY(0).getY() < j.getXY(1).getY() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(firstOfI.getY(), firstOfJ.getY(), threshold) ? Double.compare(firstOfI.getX(), firstOfJ.getX()) : Double.compare(firstOfI.getY(), firstOfJ.getY()));
}});
ArrayList<SVGLine> lines3 = (ArrayList<SVGLine>) lines1.clone();
Collections.reverse(lines3);
ArrayList<SVGLine> lines4 = (ArrayList<SVGLine>) lines1.clone();
ArrayList<SVGLine> lines5 = (ArrayList<SVGLine>) lines1.clone();
Collections.sort(lines4, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 secondOfI = (i.getXY(0).getX() >= i.getXY(1).getX() ? i.getXY(0) : i.getXY(1));
Real2 secondOfJ = (j.getXY(0).getX() >= j.getXY(1).getX() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(secondOfI.getX(), secondOfJ.getX(), threshold) ? Double.compare(secondOfI.getY(), secondOfJ.getY()) : Double.compare(secondOfI.getX(), secondOfJ.getX()));
}});
Collections.sort(lines5, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
Real2 secondOfI = (i.getXY(0).getY() >= i.getXY(1).getY() ? i.getXY(0) : i.getXY(1));
Real2 secondOfJ = (j.getXY(0).getY() >= j.getXY(1).getY() ? j.getXY(0) : j.getXY(1));
return (Real.isEqual(secondOfI.getY(), secondOfJ.getY(), threshold) ? Double.compare(secondOfI.getX(), secondOfJ.getX()) : Double.compare(secondOfI.getY(), secondOfJ.getY()));
}});
ArrayList<SVGLine> lines6 = (ArrayList<SVGLine>) lines4.clone();
Collections.reverse(lines6);
ArrayList<SVGLine> lines7 = (ArrayList<SVGLine>) lines1.clone();
ArrayList<SVGLine> lines8 = (ArrayList<SVGLine>) lines1.clone();
Collections.sort(lines7, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
return (Real.isEqual(i.getMidPoint().getX(), j.getMidPoint().getX(), threshold) ? Double.compare(i.getMidPoint().getY(), j.getMidPoint().getY()) : Double.compare(i.getMidPoint().getX(), j.getMidPoint().getX()));
}});
Collections.sort(lines8, new Comparator<SVGLine>(){
public int compare(SVGLine i, SVGLine j) {
return (Real.isEqual(i.getMidPoint().getY(), j.getMidPoint().getY(), threshold) ? Double.compare(i.getMidPoint().getX(), j.getMidPoint().getX()) : Double.compare(i.getMidPoint().getY(), j.getMidPoint().getY()));
}});
ArrayList<SVGLine> lines9 = (ArrayList<SVGLine>) lines7.clone();
Collections.reverse(lines9);
boolean firstEndPointsAndSecondEndPointsOrdered = ((lines1.equals(lines2) || lines3.equals(lines2)) && (lines4.equals(lines5) || lines6.equals(lines5)));
boolean firstEndPointsAndMidPointsOrdered = ((lines1.equals(lines2) || lines3.equals(lines2)) && (lines7.equals(lines8) || lines9.equals(lines8)));
boolean secondEndPointsAndMidPointsOrdered = ((lines4.equals(lines5) || lines6.equals(lines5)) && (lines7.equals(lines8) || lines9.equals(lines8)));
if (firstEndPointsAndSecondEndPointsOrdered || firstEndPointsAndMidPointsOrdered || secondEndPointsAndMidPointsOrdered) {
ArrayList<SVGLine> lines;
if (firstEndPointsAndSecondEndPointsOrdered || firstEndPointsAndMidPointsOrdered) {
lines = lines1;
} else {
lines = lines4;
}
try {
double change = lines.get(1).getLength() - lines.get(0).getLength();
double direction = Math.signum(change);
double firstLength = lines.get(0).getLength();
for (int i = 2; i < lines.size() && change > parameters.getLengthTolerance(); i++) {
if (Math.signum(lines.get(i).getLength() - firstLength) != direction) {
continue set;
}
}
} catch (IndexOutOfBoundsException e) {
}
HatchedBond hatchedBond = new HatchedBond(parameters, lines);
hatchList.add(hatchedBond);
if (lines.size() > 2) {
higherPrimitives.getLineList().removeAll(lines);
} else if (lines.size() == 2) {
mutuallyExclusiveShortLinePairTriples.add(new MutuallyExclusiveShortLinePairTriple(hatchedBond, lines.get(0), lines.get(1)));
} else {
Charge charge = null;
if (lines.get(0).isHorizontal(parameters.getFlatLineEpsilon()) && !lines.get(0).isVertical(parameters.getFlatLineEpsilon())) {
charge = new Charge(parameters, lines);
higherPrimitives.getLineChargeList().add(charge);
}
mutuallyExclusiveShortLineTriples.add(new MutuallyExclusiveShortLineTriple(hatchedBond, charge, lines.get(0)));
}
}
}
}
private void createJunctions() {
createJoinableList();
List<Joinable> joinables = higherPrimitives.getJoinableList();
List<JoinPoint> joinPoints = extractAtomLabelsAndGetRemainingJoinPoints(joinables);
UnionFind<JoinPoint> joinPointsGroupedIntoJunctions = UnionFind.create(joinPoints);
//int deleted = 0;
attemptToJoinListOfJoinables(joinables, joinPointsGroupedIntoJunctions);
try {
handleAmbiguities(joinPointsGroupedIntoJunctions);
} catch (IllegalArgumentException e) {
joinPoints.clear();
LOG.debug("Processing failed as the diagram was too complex");
}
List<Junction> junctions = new ArrayList<Junction>();
if (joinPoints.size() != 0) {
for (Set<JoinPoint> junctionJoinPoints : joinPointsGroupedIntoJunctions.snapshot()) {
//if (junctionJoinPoints.size() != 1) {
/*Set<Joinable> junctionJoinables = new HashSet<Joinable>();
Set<JoinPoint> newJunctionJoinPoints = new HashSet <JoinPoint>();
for (JoinPoint point : junctionJoinPoints) {
if (junctionJoinables.add(point.getJoinable())) {
newJunctionJoinPoints.add(point);
} else {
newJunctionJoinPoints.removeAll(point.getJoinable().getJoinPoints());
removeJoinable(point.getJoinable());
//junctionJoinables.remove(point.getJoinable());
}
}
for (Joinable j1 : junctionJoinables) {
int numberParallel = 0;
for (Joinable j2 : junctionJoinables) {
if (Joinable.areParallel(j1, j2)) {
numberParallel++;
if (numberParallel == 3) {
for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}
continue junction;
}
}
}
}
junctions.add(new Junction(newJunctionJoinPoints));*/
//}
junctions.add(new Junction(junctionJoinPoints));
}
}
higherPrimitives.setJunctionList(junctions);
/*JoinPoint commonPoint = joinablei.getIntersectionPoint(joinablej);
if (commonPoint != null) {
Junction junction = new Junction(joinablei, joinablej, commonPoint);
rawJunctionList.add(junction);
String junctAttVal = "junct"+"."+rawJunctionList.size();
junction.addAttribute(new Attribute(SVGElement.ID, junctAttVal));
if (junction.getCoordinates() == null && commonPoint.getPoint() != null) {
junction.setCoordinates(commonPoint.getPoint());
}
LOG.debug("junct: "+junction.getId()+" between " + joinablei.getClass() + " and " + joinablej.getClass() + " with coords "+junction.getCoordinates()+" "+commonPoint.getPoint());
}
}
}*/
/*createRawJunctionList();
List<Junction> junctionList = new ArrayList<Junction>(higherPrimitives.getRawJunctionList());
for (int i = junctionList.size() - 1; i > 0; i--) {
Junction labile = junctionList.get(i);
for (int j = 0; j < i; j++) {
Junction fixed = junctionList.get(j);
if (fixed.containsCommonPoints(labile)) {
labile.transferDetailsTo(fixed);
junctionList.remove(i);
break;
}
}
}
higherPrimitives.setMergedJunctionList(junctionList);*/
}
private void attemptToJoinListOfJoinables(List<Joinable> joinables, UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
List<JoinableText> texts = new ArrayList<JoinableText>();
for (int i = 0; i < joinables.size() - 1; i++) {
Joinable joinableI = joinables.get(i);
if (!(joinableI instanceof JoinableText)) {
for (int j = i + 1; j < joinables.size(); j++) {
Joinable joinableJ = joinables.get(j);
if (!(joinableJ instanceof JoinableText)) {
checkTime("Took too long to determine what is joined to what");
//System.out.println(joinableI + "\n" + joinableJ);
joinPointsGroupedIntoJunctions.unionAll(getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, joinableI, joinableJ));
}
}
} else {
texts.add((JoinableText) joinableI);
}
}
if (joinables.get(joinables.size() - 1) instanceof JoinableText) {
texts.add((JoinableText) joinables.get(joinables.size() - 1));
}
attemptToJoinTexts(texts, joinables, joinPointsGroupedIntoJunctions);
}
private void attemptToJoinTexts(List<JoinableText> texts, List<Joinable> joinables, UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
for (int i = 0; i < texts.size() - 1; i++) {
JoinableText textI = texts.get(i);
for (int j = i + 1; j < texts.size(); j++) {
JoinableText textJ = texts.get(j);
checkTime("Took too long to determine what is joined to what");
joinPointsGroupedIntoJunctions.unionAll(getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, textI, textJ));
}
}
for (JoinableText text : texts) {
Set<JoinPoint> joinPoints = new HashSet<JoinPoint>();
for (Joinable joinable : joinables) {
if (!(joinable instanceof JoinableText)) {
checkTime("Took too long to determine what is joined to what");
List<JoinPoint> overlap = getListOfOverlappingJoinPointsForJoinables(joinPointsGroupedIntoJunctions, text, joinable);
joinPoints.addAll(overlap);
for (JoinPoint j : overlap) {
if (!(j.getJoinable() instanceof JoinableText)) {
joinPoints.addAll(joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(j));
}
}
}
}
List<JoinPoint> actualJoinPoints = new ArrayList<JoinPoint>();
i: for (JoinPoint joinPointI : joinPoints) {
for (JoinPoint joinPointJ : joinPoints) {
if (joinPointI != joinPointJ && joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(joinPointI).contains(joinPointJ)) {
continue i;
}
}
actualJoinPoints.add(joinPointI);
}
joinPointsGroupedIntoJunctions.unionAll(actualJoinPoints);
}
}
private List<JoinPoint> getListOfOverlappingJoinPointsForJoinables(UnionFind<JoinPoint> joinPointsGroupedIntoJunctions, Joinable joinableI, Joinable joinableJ) {
Set<JoinPoint> overlapSet = joinableI.overlapWith(joinableJ);
if (overlapSet != null) {
List<JoinPoint> overlapList = new ArrayList<JoinPoint>(overlapSet);
if (!joinPointsGroupedIntoJunctions.contains(overlapList.get(0)) || !joinPointsGroupedIntoJunctions.contains(overlapList.get(1)) || (overlapList.size() > 2 && !joinPointsGroupedIntoJunctions.contains(overlapList.get(2))) || (overlapList.size() > 3 && !joinPointsGroupedIntoJunctions.contains(overlapList.get(3)))) {
return new ArrayList<JoinPoint>();
}
if (mutuallyExclusive(joinableI, joinableJ)) {
return new ArrayList<JoinPoint>();
}
if (joinableI instanceof JoinableText && joinableJ instanceof JoinableText) {
if (JoinableText.doTextsJoin((JoinableText) joinableI, (JoinableText) joinableJ, parameters)) {
//joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));
return overlapList;
}
} else if ((joinableI instanceof JoinableText && joinableJ.getJoinPoints().size() == 2) || (joinableJ instanceof JoinableText && joinableI.getJoinPoints().size() == 2)) {
Joinable lineJoinable = (joinableI instanceof JoinableText ? joinableJ : joinableI);
JoinPoint lineJoinEnd = (overlapList.get(0).getJoinable() instanceof JoinableText ? overlapList.get(1) : overlapList.get(0));
JoinPoint lineOtherEnd = (lineJoinable.getJoinPoints().get(0) == lineJoinEnd ? lineJoinable.getJoinPoints().get(1) : lineJoinable.getJoinPoints().get(0));
Line2 line = new Line2(lineOtherEnd.getPoint(), lineJoinEnd.getPoint());
JoinPoint text = (overlapList.get(0).getJoinable() instanceof JoinableText ? overlapList.get(0) : overlapList.get(1));
Line2 testLine = new Line2(lineJoinEnd.getPoint(), text.getPoint());
if (isNumber((SVGText) text.getJoinable().getSVGElement()) || line.isParallelTo(testLine, new Angle(parameters.getTightBondAndTextAngle(), Units.DEGREES))) {
return overlapList;
} else {
text.setRadius(text.getRadius() * parameters.getSmallRadiusExpansion() / parameters.getLargeRadiusExpansion());
Set<JoinPoint> overlapSet2 = joinableI.overlapWith(joinableJ);
text.setRadius(text.getRadius() * parameters.getLargeRadiusExpansion() / parameters.getSmallRadiusExpansion());
if (overlapSet2 != null && line.isParallelTo(testLine, new Angle(parameters.getLooseBondAndTextAngle(), Units.DEGREES))) {
return overlapList;
}
}
} else {
return overlapList;
}
/*if (joinableI instanceof JoinableText && joinableJ instanceof JoinableText) {
if (doTextsJoin(joinableI, joinableJ)) {
joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));
}
} else {
joinPointsGroupedIntoJunctions.union(overlap.get(0), overlap.get(1));*/
/*if (joinableI instanceof HatchedBond) {
joinables.remove(whichLineIsWhichSingleBond.get(mutuallyExclusivePairs.get(joinableI)));
}
if (joinableJ instanceof HatchedBond) {
joinables.remove(whichLineIsWhichSingleBond.get(mutuallyExclusivePairs.get(joinableJ)));
}
if (joinableI instanceof SingleBond) {
joinables.remove(mutuallyExclusivePairs.inverse().get(joinableI));
}
if (joinableJ instanceof SingleBond) {
joinables.remove(mutuallyExclusivePairs.inverse().get(joinableJ));
}*/
//}
/*if (joinablei instanceof JoinableScriptWord && joinablej instanceof JoinableScriptWord) {
if (!((JoinableScriptWord) joinablei).getScriptWord().toUnderscoreAndCaretString().equals("H") && !((JoinableScriptWord) joinablej).getScriptWord().toUnderscoreAndCaretString().equals("H")) {
continue;
}
}*/
}
return new ArrayList<JoinPoint>();
}
private void removeJoinable(Joinable joinable) {
higherPrimitives.getJoinableList().remove(joinable);
higherPrimitives.getDoubleBondList().remove(joinable);
higherPrimitives.getHatchedBondList().remove(joinable);
higherPrimitives.getLineChargeList().remove(joinable);
}
private void handleAmbiguities(UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) {
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
JoinPoint singleBondFirst = triple.singleBond.getJoinPoints().get(0);
JoinPoint singleBondSecond = triple.singleBond.getJoinPoints().get(1);
JoinPoint hatchedBondFirst = triple.hatchedBond.getJoinPoints().get(0);
JoinPoint hatchedBondSecond = triple.hatchedBond.getJoinPoints().get(1);
JoinPoint minus = (triple.minus == null ? null : triple.minus.getJoinPoints().get(0));
if (joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondSecond) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) > 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) > 1) {
if (minus != null) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(minus);
joinPointsGroupedIntoJunctions.explode(points);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p : points) {
if (p.getJoinable() != triple.minus) {
joinables.add(p.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
}
joinPointsGroupedIntoJunctions.remove(singleBondFirst);
joinPointsGroupedIntoJunctions.remove(singleBondSecond);
joinPointsGroupedIntoJunctions.remove(minus);
removeJoinable(triple.singleBond);
higherPrimitives.getLineList().remove(triple.line);
removeJoinable(triple.minus);
} else if (joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(singleBondSecond) == 1 && (joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) == 1 || joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) == 1) && minus != null) {
joinPointsGroupedIntoJunctions.remove(singleBondFirst);
joinPointsGroupedIntoJunctions.remove(singleBondSecond);
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
removeJoinable(triple.singleBond);
higherPrimitives.getLineList().remove(triple.line);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.hatchedBond);
} else {
if (minus != null) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(minus);
joinPointsGroupedIntoJunctions.explode(points);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p : points) {
if (p.getJoinable() != triple.minus) {
joinables.add(p.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
}
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
joinPointsGroupedIntoJunctions.remove(minus);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.minus);
removeJoinable(triple.hatchedBond);
removeJoinable(triple.minus);
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
joinPointsGroupedIntoJunctions.remove(triple.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(triple.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(triple.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(triple.singleBond2.getJoinPoints().get(1));
removeJoinable(triple.singleBond1);
removeJoinable(triple.singleBond2);
higherPrimitives.getLineList().remove(triple.line1);
higherPrimitives.getLineList().remove(triple.line2);
if (triple.doubleBond == null) {
continue;
}
JoinPoint doubleBondFirst = triple.doubleBond.getJoinPoints().get(0);
JoinPoint doubleBondSecond = triple.doubleBond.getJoinPoints().get(1);
JoinPoint hatchedBondFirst = triple.hatchedBond.getJoinPoints().get(0);
JoinPoint hatchedBondSecond = triple.hatchedBond.getJoinPoints().get(1);
if ((joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondFirst) > 1 || joinPointsGroupedIntoJunctions.getSizeOfPartition(hatchedBondSecond) > 1) && joinPointsGroupedIntoJunctions.getSizeOfPartition(doubleBondFirst) == 1 && joinPointsGroupedIntoJunctions.getSizeOfPartition(doubleBondSecond) == 1) {
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(triple.doubleBond);
} else {
joinPointsGroupedIntoJunctions.remove(hatchedBondFirst);
joinPointsGroupedIntoJunctions.remove(hatchedBondSecond);
removeJoinable(triple.hatchedBond);
}
}
Set<SingleBond> singleBonds = new HashSet<SingleBond>();
for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
singleBonds.add(pair.singleBond1);
singleBonds.add(pair.singleBond2);
}
pair: for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
JoinPoint doubleBondFirst = pair.doubleBond.getJoinPoints().get(0);
JoinPoint doubleBondSecond = pair.doubleBond.getJoinPoints().get(1);
boolean sewn = joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondFirst).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond1.getJoinPoints().get(1)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(0)));
sewn |= joinPointsGroupedIntoJunctions.get(doubleBondSecond).equals(joinPointsGroupedIntoJunctions.get(pair.singleBond2.getJoinPoints().get(1)));
if (sewn) {
Set<JoinPoint> points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(doubleBondFirst);
boolean foundParallel = false;
for (JoinPoint p1 : points) {
if (!(p1.getJoinable() instanceof DoubleBond) && !singleBonds.contains(p1.getJoinable()) && Joinable.areParallel(p1.getJoinable(), pair.doubleBond, new Angle(parameters.getToleranceForParallelJoinables(), Units.RADIANS))) {
if (foundParallel) {
joinPointsGroupedIntoJunctions.explode(points);
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(pair.doubleBond);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p2 : points) {
if (p2.getJoinable() != pair.doubleBond) {
joinables.add(p2.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
/*for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}*/
continue pair;
} else {
foundParallel = true;
}
}
}
points = joinPointsGroupedIntoJunctions.getObjectsInPartitionOf(doubleBondSecond);
foundParallel = false;
for (JoinPoint p1 : points) {
if (!(p1.getJoinable() instanceof DoubleBond) && !singleBonds.contains(p1.getJoinable()) && Joinable.areParallel(p1.getJoinable(), pair.doubleBond, new Angle(parameters.getToleranceForParallelJoinables(), Units.RADIANS))) {
if (foundParallel) {
joinPointsGroupedIntoJunctions.explode(points);
joinPointsGroupedIntoJunctions.remove(doubleBondFirst);
joinPointsGroupedIntoJunctions.remove(doubleBondSecond);
removeJoinable(pair.doubleBond);
Set<Joinable> joinables = new HashSet<Joinable>();
for (JoinPoint p2 : points) {
if (p2.getJoinable() != pair.doubleBond) {
joinables.add(p2.getJoinable());
}
}
attemptToJoinListOfJoinables(new ArrayList<Joinable>(joinables), joinPointsGroupedIntoJunctions);
/*for (JoinPoint p : newJunctionJoinPoints) {
junctions.add(new Junction(p));
}*/
continue pair;
} else {
foundParallel = true;
}
}
}
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(1));
higherPrimitives.getLineList().remove(pair.line1);
higherPrimitives.getLineList().remove(pair.line2);
removeJoinable(pair.singleBond1);
removeJoinable(pair.singleBond2);
} else {
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond1.getJoinPoints().get(1));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(0));
joinPointsGroupedIntoJunctions.remove(pair.singleBond2.getJoinPoints().get(1));
higherPrimitives.getLineList().remove(pair.line1);
higherPrimitives.getLineList().remove(pair.line2);
removeJoinable(pair.singleBond1);
removeJoinable(pair.singleBond2);
}
}
}
private boolean mutuallyExclusive(Joinable joinableI, Joinable joinableJ) {
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
if (joinableI == triple.hatchedBond && joinableJ == triple.minus || joinableJ == triple.hatchedBond && joinableI == triple.minus) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond || joinableJ == triple.hatchedBond && joinableI == triple.singleBond) {
return true;
}
if (joinableI == triple.singleBond && joinableJ == triple.minus || joinableJ == triple.singleBond && joinableI == triple.minus) {
return true;
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
if (joinableI == triple.hatchedBond && joinableJ == triple.doubleBond || joinableJ == triple.hatchedBond && joinableI == triple.doubleBond) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond1 || joinableJ == triple.hatchedBond && joinableI == triple.singleBond1) {
return true;
}
if (joinableI == triple.singleBond1 && joinableJ == triple.doubleBond || joinableJ == triple.singleBond1 && joinableI == triple.doubleBond) {
return true;
}
if (joinableI == triple.hatchedBond && joinableJ == triple.singleBond2 || joinableJ == triple.hatchedBond && joinableI == triple.singleBond2) {
return true;
}
if (joinableI == triple.doubleBond && joinableJ == triple.singleBond2 || joinableJ == triple.doubleBond && joinableI == triple.singleBond2) {
return true;
}
if (joinableI == triple.singleBond1 && joinableJ == triple.singleBond2 || joinableJ == triple.singleBond1 && joinableI == triple.singleBond2) {
return true;
}
}
/*for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
if (joinableI == pair.singleBond2 && joinableJ == pair.doubleBond || joinableJ == pair.singleBond2 && joinableI == pair.doubleBond) {
return true;
}
if (joinableI == pair.singleBond2 && joinableJ == pair.singleBond1 || joinableJ == pair.singleBond2 && joinableI == pair.singleBond1) {
return true;
}
if (joinableI == pair.singleBond1 && joinableJ == pair.doubleBond || joinableJ == pair.singleBond1 && joinableI == pair.doubleBond) {
return true;
}
}*/
return false;
}
private List<JoinPoint> extractAtomLabelsAndGetRemainingJoinPoints(List<Joinable> joinables) {
List<JoinPoint> remainingJoinPoints = new ArrayList<JoinPoint>();
Map<Double, List<JoinableText>> listsOfTextsByFontSize = new LinkedHashMap<Double, List<JoinableText>>();
for (Joinable j : joinables) {
if (j instanceof JoinableText) {// && isLabel(((JoinableText) j).getSVGElement())) {// && !"1".equals(((JoinableText) j).getSVGElement().getText()) && !"2".equals(((JoinableText) j).getSVGElement().getText()) && !"3".equals(((JoinableText) j).getSVGElement().getText()) && !"4".equals(((JoinableText) j).getSVGElement().getText())) {
List<JoinableText> joinablesForSize = listsOfTextsByFontSize.get(((JoinableText) j).getSVGElement().getFontSize());
if (joinablesForSize == null) {
joinablesForSize = new ArrayList<JoinableText>();
listsOfTextsByFontSize.put(((JoinableText) j).getSVGElement().getFontSize(), joinablesForSize);
}
joinablesForSize.add((JoinableText) j);
} else {
remainingJoinPoints.addAll(j.getJoinPoints());
}
}
double fontSizeOfLabels = Double.MAX_VALUE;
list: for (Entry<Double, List<JoinableText>> list : listsOfTextsByFontSize.entrySet()) {
AreInSameStringDetector sameString = new AreInSameStringDetector(list.getValue(), parameters, false, true);
ImmutableCollection<Set<Joinable>> groups = sameString.texts.snapshot();
//List<Integer> labelNumbers = new ArrayList<Integer>();
Map<Real2Range, Integer> labelNumbers = new LinkedHashMap<Real2Range, Integer>();
group: for (Set<Joinable> group : groups) {
List<Joinable> potentialLabelTexts = new ArrayList<Joinable>(group);
Joinable.sortJoinablesByX(potentialLabelTexts);
String number = "";
Real2Range bounds = new Real2Range();
for (Joinable potentialLabelText : potentialLabelTexts) {
if (!isLabel((SVGText) potentialLabelText.getSVGElement())) {
for (Joinable t : group) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
continue group;
}
bounds.add(potentialLabelText.getJoinPoints().get(0).getPoint());
if (isNumber((SVGText) potentialLabelText.getSVGElement())) {
number += ((SVGText) potentialLabelText.getSVGElement()).getText();
}
}
try {
labelNumbers.put(bounds, Integer.parseInt(number));
} catch (NumberFormatException e) {
}
}
List<Integer> labelNumbersToBeSorted = new ArrayList<Integer>(labelNumbers.values());
Collections.sort(labelNumbersToBeSorted);
int previousPreviousLabel = 0;
int previousLabel = 0;
for (Integer i : labelNumbersToBeSorted) {
if (i - previousLabel > labelNumbersToBeSorted.get(labelNumbersToBeSorted.size() - 1) * parameters.getMaximumLabelSequenceGap()) {
for (JoinableText t : list.getValue()) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
continue list;
}
previousPreviousLabel = previousLabel;
previousLabel = i;
}
if (list.getKey() < fontSizeOfLabels && labelNumbers.size() > 1) {
if (atomLabelTexts != null) {
for (JoinableText t : atomLabelTexts) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
}
atomLabelTexts = list.getValue();
atomLabelPositionsAndNumbers = labelNumbers;
fontSizeOfLabels = list.getKey();
} else {
for (JoinableText t : list.getValue()) {
remainingJoinPoints.addAll(t.getJoinPoints());
}
}
}
if (atomLabelTexts == null) {
atomLabelTexts = new ArrayList<JoinableText>();
atomLabelPositionsAndNumbers = new HashMap<Real2Range, Integer>();
}
return remainingJoinPoints;
}
private boolean isLetter(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[A-Za-z]"));
}
private boolean isNumber(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[0-9]"));
}
private boolean isLabel(SVGText svgElement) {
return (svgElement.getText() == null ? false : svgElement.getText().matches("[0-9'a]"));
}
protected void createJoinableList() {
List<Joinable> joinableList = createJoinableList(higherPrimitives.getLineList());
joinableList.addAll(createJoinableList(derivedPrimitives.getPolygonList()));
joinableList.addAll(createJoinableList(derivedPrimitives.getPathList()));
joinableList.addAll(higherPrimitives.getDoubleBondList());
joinableList.addAll(higherPrimitives.getHatchedBondList());
joinableList.addAll(higherPrimitives.getLineChargeList());
//joinableList.addAll(higherPrimitives.getWordList());
joinableList.addAll(createJoinableList(derivedPrimitives.getTextList()));
//joinableList.addAll(createJoinableList(derivedPrimitives.getImageList()));
higherPrimitives.addJoinableList(joinableList);
}
public List<Joinable> createJoinableList(List<? extends SVGElement> elementList) {
List<Joinable> joinableList = new ArrayList<Joinable>();
for (SVGElement element : elementList) {
Joinable joinable = createJoinable(element);
if (joinable != null) {
joinableList.add(joinable);
}
}
return joinableList;
}
private Joinable createJoinable(SVGElement element) {
Joinable joinable = null;
if (element instanceof SVGLine) {
joinable = new SingleBond(parameters, (SVGLine) element);
for (MutuallyExclusiveShortLineTriple triple : mutuallyExclusiveShortLineTriples) {
if (triple.line == element) {
triple.singleBond = (SingleBond) joinable;
}
}
for (MutuallyExclusiveShortLinePairTriple triple : mutuallyExclusiveShortLinePairTriples) {
if (triple.line1 == element) {
triple.singleBond1 = (SingleBond) joinable;
}
if (triple.line2 == element) {
triple.singleBond2 = (SingleBond) joinable;
}
}
for (MutuallyExclusiveLinePairPair pair : mutuallyExclusiveLinePairPairs) {
if (pair.line1 == element) {
pair.singleBond1 = (SingleBond) joinable;
}
if (pair.line2 == element) {
pair.singleBond2 = (SingleBond) joinable;
}
}
} else if (element instanceof SVGText) {
if (("+".equals(((SVGText) element).getText()) || "-".equals(((SVGText) element).getText())) && !JoinableText.anyTextsInSameString((SVGText) element, derivedPrimitives.getTextList(), parameters, false, true) && !JoinableText.anyTextsToRightInSameString((SVGText) element, derivedPrimitives.getTextList(), parameters, true)) {
joinable = new Charge(parameters, (SVGText) element);
} else {
joinable = new JoinableText(parameters, (SVGText) element);
}
} else if (element instanceof SVGPolygon && ((SVGPolygon) element).createLineList(true).size() == 3) {
double shortest = Double.MAX_VALUE;
for (SVGLine line : ((SVGPolygon) element).getLineList()) {
if (line.getLength() < shortest) {
shortest = line.getLength();
}
}
if (shortest > 0.5) {
joinable = new WedgeBond(parameters, (SVGPolygon) element);
wedgeBonds.add((WedgeBond) joinable);
}
} else if (element instanceof SVGPolygon && ((SVGPolygon) element).createLineList(true).size() == 4) {
for (int i = 0; i < ((SVGPolygon) element).getReal2Array().size(); i++) {
Real2Array withoutPoint = new Real2Array(((SVGPolygon) element).getReal2Array());
Real2 deleted = withoutPoint.get(i);
withoutPoint.deleteElement(i);
SVGPolygon newPoly = new SVGPolygon(withoutPoint);
if (newPoly.containsPoint(deleted, 0)) {//withoutPoint.getRange2().includes(((SVGPolygon) element).getReal2Array().get(i))) {
((SVGPolygon) element).setReal2Array(withoutPoint);
joinable = new WedgeBond(parameters, (SVGPolygon) element);
wedgeBonds.add((WedgeBond) joinable);
break;
}
}
} else if (element instanceof SVGPath) {
try {
joinable = new WigglyBond(parameters, (SVGPath) element);
} catch (IllegalArgumentException e) {
}
}
if (joinable == null) {
LOG.debug("Unknown joinable: " + element);
}
return joinable;
}
private void createDoubleBondList() {
DoubleBondManager doubleBondManager = new DoubleBondManager(parameters);
List<DoubleBond> doubleBondList;
try {
doubleBondList = doubleBondManager.createDoubleBondListWithoutReusingLines(higherPrimitives.getLineList(), startTime + timeout - System.currentTimeMillis());
} catch (TimeoutException e) {
throw new UncheckedTimeoutException(e.getMessage());
}
//doubleBondManager.removeUsedDoubleBondPrimitives(higherPrimitives.getLineList());
higherPrimitives.setDoubleBondList(doubleBondList);
mutuallyExclusiveLinePairPairs = new ArrayList<ChemistryBuilder.MutuallyExclusiveLinePairPair>();
bond: for (DoubleBond bond : doubleBondList) {
for (MutuallyExclusiveShortLinePairTriple pair : mutuallyExclusiveShortLinePairTriples) {
if ((pair.line1 == bond.getLine(0) && pair.line2 == bond.getLine(1)) || (pair.line1 == bond.getLine(1) && pair.line2 == bond.getLine(0))) {
pair.doubleBond = bond;
continue bond;
}
}
mutuallyExclusiveLinePairPairs.add(new MutuallyExclusiveLinePairPair(bond));
//higherPrimitives.getLineList().add(bond.getLine(0));
//higherPrimitives.getLineList().add(bond.getLine(1));
}
}
/*private void createRawJunctionList() {
createJoinableList();
List<Joinable> joinableList = higherPrimitives.getJoinableList();
List<Junction> rawJunctionList = new ArrayList<Junction>();
for (int i = 0; i < joinableList.size() - 1; i++) {
Joinable joinablei = joinableList.get(i);
for (int j = i + 1; j < joinableList.size(); j++) {
Joinable joinablej = joinableList.get(j);
JoinPoint commonPoint = joinablei.getIntersectionPoint(joinablej);
if (commonPoint != null) {
Junction junction = new Junction(joinablei, joinablej, commonPoint);
rawJunctionList.add(junction);
String junctAttVal = "junct"+"."+rawJunctionList.size();
junction.addAttribute(new Attribute(SVGElement.ID, junctAttVal));
if (junction.getCoordinates() == null && commonPoint.getPoint() != null) {
junction.setCoordinates(commonPoint.getPoint());
}
LOG.debug("junct: "+junction.getId()+" between " + joinablei.getClass() + " and " + joinablej.getClass() + " with coords "+junction.getCoordinates()+" "+commonPoint.getPoint());
}
}
}
higherPrimitives.setRawJunctionList(rawJunctionList);
}*/
public SVGElement getSVGRoot() {
return svgRoot;
}
public HigherPrimitives getHigherPrimitives() {
return higherPrimitives;
}
public Map<Real2Range, Integer> getAtomLabels() {
return atomLabelPositionsAndNumbers;
}
void draw() {
draw(new File("target/chem/andy.svg"));
}
public void draw(File file) {
SVGG out = drawPrimitivesJoinPointsAndJunctions();
SVGSVG.wrapAndWriteAsSVG(out, file);
}
SVGG drawPrimitivesJoinPointsAndJunctions() {
SVGG out = new SVGG();
SVGG circles = new SVGG();
out.appendChild(circles);
if (higherPrimitives.getJunctionList() != null) {
for (Junction j : higherPrimitives.getJunctionList()) {
Real2 coords = (j.getCoordinates() == null ? new Real2(0, 0) : j.getCoordinates());
SVGCircle c = new SVGCircle(coords, 1.2);
c.setFill("#555555");
c.setOpacity(0.7);
c.setStrokeWidth(0.0);
circles.appendChild(c);
SVGText t = new SVGText(coords.plus(new Real2(1.5, Math.random() * 6)), j.getID());
circles.appendChild(t);
for (JoinPoint point : j.getJoinPoints()) {
SVGLine line = new SVGLine(coords, point.getPoint());
line.setStrokeWidth(0.05);
circles.appendChild(line);
}
}
}
for (SVGText t : getDerivedPrimitives().getTextList()) {
SVGText o = (SVGText) t.copy();
out.appendChild(o);
}
for (SVGLine l : getDerivedPrimitives().getLineList()) {
SVGLine o = (SVGLine) l.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (SVGPolygon p : getDerivedPrimitives().getPolygonList()) {
SVGPolygon o = (SVGPolygon) p.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (SVGPath p : getDerivedPrimitives().getPathList()) {
SVGPath o = (SVGPath) p.copy();
o.setStrokeWidth(0.4);
out.appendChild(o);
}
for (Charge t : getHigherPrimitives().getLineChargeList()) {
if (t.getSVGElement() != null) {
SVGElement e = (SVGElement) t.getSVGElement().copy();
out.appendChild(e);
}
}
/*for (SVGImage t : simpleBuilder.getDerivedPrimitives().getImageList()) {
SVGText e = new SVGText
out.appendChild(e);
}*/
if (getHigherPrimitives().getJoinableList() != null) {
for (Joinable j : getHigherPrimitives().getJoinableList()) {
for (JoinPoint p : j.getJoinPoints()) {
Real2 coords = (p.getPoint() == null ? new Real2(0, 0) : p.getPoint());
SVGCircle c = new SVGCircle(coords, p.getRadius());
if (j instanceof SingleBond) {
c.setFill("#9999FF");
} else if (j instanceof DoubleBond) {
c.setFill("#99FF99");
} else if (j instanceof HatchedBond) {
c.setFill("#FF9999");
} else if (j instanceof WedgeBond) {
c.setFill("#99FFFF");
} else if (j instanceof Charge) {
c.setFill("#FFFF99");
} else if (j instanceof JoinableText) {
c.setFill("#FF99FF");
} else if (j instanceof WigglyBond) {
c.setFill("#999999");
}
c.setOpacity(0.7);
c.setStrokeWidth(0.0);
circles.appendChild(c);
//SVGText t = new SVGText(coords.plus(new Real2(1.5, Math.random() * 6)), j.getId());
//out.appendChild(t);
}
}
}
return out;
}
} | Added check for whether there are actually any joinables before starting text-joining process.
| src/main/java/org/xmlcml/ami2/chem/ChemistryBuilder.java | Added check for whether there are actually any joinables before starting text-joining process. | <ide><path>rc/main/java/org/xmlcml/ami2/chem/ChemistryBuilder.java
<ide> texts.add((JoinableText) joinableI);
<ide> }
<ide> }
<del> if (joinables.get(joinables.size() - 1) instanceof JoinableText) {
<del> texts.add((JoinableText) joinables.get(joinables.size() - 1));
<del> }
<del> attemptToJoinTexts(texts, joinables, joinPointsGroupedIntoJunctions);
<add> if (joinables.size() > 0) {
<add> if (joinables.get(joinables.size() - 1) instanceof JoinableText) {
<add> texts.add((JoinableText) joinables.get(joinables.size() - 1));
<add> }
<add> attemptToJoinTexts(texts, joinables, joinPointsGroupedIntoJunctions);
<add> }
<ide> }
<ide>
<ide> private void attemptToJoinTexts(List<JoinableText> texts, List<Joinable> joinables, UnionFind<JoinPoint> joinPointsGroupedIntoJunctions) { |
|
Java | apache-2.0 | 72ed7599cd236fcdf3469a25336f21664f4c796a | 0 | reactor/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core | /*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.Producer;
import reactor.core.Receiver;
import reactor.core.Trackable;
/**
* Emits a single item at most from the source.
*
* @param <T> the value type
* @see <a href="https://github.com/reactor/reactive-streams-commons">Reactive-Streams-Commons</a>
*/
final class MonoNext<T> extends MonoSource<T, T> {
public MonoNext(Publisher<? extends T> source) {
super(source);
}
@Override
public void subscribe(Subscriber<? super T> s) {
source.subscribe(new NextSubscriber<>(s));
}
static final class NextSubscriber<T>
implements Subscriber<T>, Subscription, Receiver, Producer, Trackable {
final Subscriber<? super T> actual;
Subscription s;
boolean done;
volatile int wip;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<NextSubscriber> WIP =
AtomicIntegerFieldUpdater.newUpdater(NextSubscriber.class, "wip");
public NextSubscriber(Subscriber<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
actual.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (done) {
Operators.onNextDropped(t);
return;
}
s.cancel();
actual.onNext(t);
onComplete();
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t);
return;
}
done = true;
actual.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
actual.onComplete();
}
@Override
public void request(long n) {
if (WIP.compareAndSet(this, 0, 1)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public void cancel() {
s.cancel();
}
@Override
public boolean isStarted() {
return s != null && !done;
}
@Override
public boolean isTerminated() {
return done;
}
@Override
public long getCapacity() {
return 1L;
}
@Override
public Object upstream() {
return s;
}
@Override
public Object downstream() {
return actual;
}
}
}
| src/main/java/reactor/core/publisher/MonoNext.java | /*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.Producer;
import reactor.core.Receiver;
import reactor.core.Trackable;
/**
* Emits a single item at most from the source.
*
* @param <T> the value type
* @see <a href="https://github.com/reactor/reactive-streams-commons">Reactive-Streams-Commons</a>
*/
final class MonoNext<T> extends MonoSource<T, T> {
public MonoNext(Publisher<? extends T> source) {
super(source);
}
@Override
public void subscribe(Subscriber<? super T> s) {
source.subscribe(new NextSubscriber<>(s));
}
static final class NextSubscriber<T>
implements Subscriber<T>, Subscription, Receiver, Producer, Trackable {
final Subscriber<? super T> actual;
Subscription s;
boolean done;
volatile int wip;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<NextSubscriber> WIP =
AtomicIntegerFieldUpdater.newUpdater(NextSubscriber.class, "wip");
public NextSubscriber(Subscriber<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
actual.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
if (done) {
Operators.onNextDropped(t);
return;
}
s.cancel();
actual.onNext(t);
onComplete();
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t);
return;
}
done = true;
actual.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
actual.onComplete();
}
@Override
public void request(long n) {
if (WIP.compareAndSet(this, 0, 1)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public void cancel() {
s.cancel();
}
@Override
public boolean isStarted() {
return s != null && !done;
}
@Override
public boolean isTerminated() {
return done;
}
@Override
public long getCapacity() {
return 1L;
}
@Override
public Object upstream() {
return s;
}
@Override
public Object downstream() {
return actual;
}
}
}
| tweak autoRead false
| src/main/java/reactor/core/publisher/MonoNext.java | tweak autoRead false | <ide><path>rc/main/java/reactor/core/publisher/MonoNext.java
<del>/*
<add> /*
<ide> * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License"); |
|
Java | apache-2.0 | b0cb0a806a67a641b883f3f09b2d38f18df670b5 | 0 | OpenHFT/Chronicle-Network | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.network.cluster;
/**
* @author Rob Austin.
*/
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.network.WireTcpHandler;
import net.openhft.chronicle.wire.Demarshallable;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import net.openhft.chronicle.wire.WriteMarshallable;
import org.jetbrains.annotations.NotNull;
/**
* Handles the connection strategy ( in other words when to accept or reject a connection ) and
* heart beating )
*
* @author Rob Austin.
*/
public class HostIdConnectionStrategy implements ConnectionStrategy, Demarshallable, WriteMarshallable {
@UsedViaReflection
private HostIdConnectionStrategy(WireIn w) {
}
HostIdConnectionStrategy() {
}
/**
* @return false if already connected
*/
public synchronized boolean notifyConnected(@NotNull WireTcpHandler handler,
int localIdentifier,
int remoteIdentifier) {
if (!handler.nc().isAcceptor())
return true;
return localIdentifier > remoteIdentifier;
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
}
}
| src/main/java/net/openhft/chronicle/network/cluster/HostIdConnectionStrategy.java | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.network.cluster;
/**
* @author Rob Austin.
*/
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.network.WireTcpHandler;
import net.openhft.chronicle.wire.Demarshallable;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import net.openhft.chronicle.wire.WriteMarshallable;
import org.jetbrains.annotations.NotNull;
/**
* Handles the connection strategy ( in other words when to accept or reject a connection ) and
* heart beating )
*
* @author Rob Austin.
*/
public class HostIdConnectionStrategy implements ConnectionStrategy, Demarshallable, WriteMarshallable {
@UsedViaReflection
private HostIdConnectionStrategy(WireIn w) {
}
HostIdConnectionStrategy() {
}
/**
* @return false if already connected
*/
public synchronized boolean notifyConnected(@NotNull WireTcpHandler handler,
int localIdentifier,
int remoteIdentifier) {
return !(handler.nc().isAcceptor() && localIdentifier < remoteIdentifier);
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
}
}
| chagned stratagy
| src/main/java/net/openhft/chronicle/network/cluster/HostIdConnectionStrategy.java | chagned stratagy | <ide><path>rc/main/java/net/openhft/chronicle/network/cluster/HostIdConnectionStrategy.java
<ide> int localIdentifier,
<ide> int remoteIdentifier) {
<ide>
<del> return !(handler.nc().isAcceptor() && localIdentifier < remoteIdentifier);
<add> if (!handler.nc().isAcceptor())
<add> return true;
<add>
<add> return localIdentifier > remoteIdentifier;
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | e7ed504f8367c069ea4ac9cac17aa8b422190527 | 0 | camwest/cog | var Site = require('./models').Site
, User = require('./models').User;
var NO_SITE = 'Site not created';
module.exports = {
NO_SITE: NO_SITE,
exists: function(callback) {
Site.findOne({}, function(err, site) {
if (err || !site) {
return callback(NO_SITE);
}
callback(null, site);
});
},
create: function(userParams, callback) {
Site.create({}, function(err, site) {
if (err) {
callback(err);
}
// add site id to user
userParams.siteId = site.id;
User.create(userParams, function(err, user) {
if (err) {
callback(err);
}
callback(null, site);
});
});
},
update: function(siteId, update, callback) {
Site.findOneAndUpdate({ _id: siteId }, update, callback);
},
destroyAll: function(callback) {
Site.remove({}, callback);
}
};
| server/src/services/site.js | var Site = require('./models').Site
, User = require('./models').User;
var NO_SITE = 'Site not created';
module.exports = {
NO_SITE: NO_SITE,
exists: function(callback) {
Site.findOne({}, function(err, site) {
if (err || !site) {
return callback(NO_SITE);
}
callback(null, site);
});
},
create: function(userParams, callback) {
Site.create({}, function(err, site) {
if (err) {
callback(err);
}
// add site id to user
userParams.siteId = site.id;
User.create(userParams, function(err, user) {
if (err) {
callback(err);
}
callback(null, site);
});
});
},
//TODO: refactor
fetch: function(siteId, callback) {
Site.findById(siteId, callback);
},
update: function(siteId, update, callback) {
Site.findOneAndUpdate({ _id: siteId }, update, callback);
},
destroyAll: function(callback) {
Site.remove({}, callback);
}
};
| Removed un-used function
| server/src/services/site.js | Removed un-used function | <ide><path>erver/src/services/site.js
<ide> });
<ide> },
<ide>
<del> //TODO: refactor
<del> fetch: function(siteId, callback) {
<del> Site.findById(siteId, callback);
<del> },
<del>
<ide> update: function(siteId, update, callback) {
<ide> Site.findOneAndUpdate({ _id: siteId }, update, callback);
<ide> }, |
|
JavaScript | apache-2.0 | 1fd31480eef4b3ecf28d1ef7bea9acaa1ee45ec0 | 0 | polyvi/xface-mobile-spec,ollie314/cordova-mobile-spec,corimf/cordova-mobile-spec,apache/cordova-mobile-spec,polyvi/xface-mobile-spec,ollie314/cordova-mobile-spec,ollie314/cordova-mobile-spec,apache/cordova-mobile-spec,apache/cordova-mobile-spec,polyvi/xface-mobile-spec,ollie314/cordova-mobile-spec,apache/cordova-mobile-spec,corimf/cordova-mobile-spec,ollie314/cordova-mobile-spec,corimf/cordova-mobile-spec,apache/cordova-mobile-spec,corimf/cordova-mobile-spec,corimf/cordova-mobile-spec | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
if (window.sessionStorage != null) {
window.sessionStorage.clear();
}
// Timeout is 2 seconds to allow physical devices enough
// time to query the response. This is important for some
// Android devices.
var Tests = function() {};
Tests.TEST_TIMEOUT = 7500;
// Creates a spy that will fail if called.
function createDoNotCallSpy(name, opt_extraMessage) {
return jasmine.createSpy().andCallFake(function() {
var errorMessage = "" + name + ' should not have been called.';
try {
if (arguments.length) {
errorMessage += ' Got args: ' + JSON.stringify(arguments);
}
if (opt_extraMessage) {
errorMessage += '\n' + opt_extraMessage;
}
} catch(e) {
errorMessage += " (Cannot print details)";
}
expect(false).toBe(true, errorMessage);
});
}
// Waits for any of the given spys to be called.
// Last param may be a custom timeout duration.
function waitsForAny() {
var spys = [].slice.call(arguments);
var timeout = Tests.TEST_TIMEOUT;
if (typeof spys[spys.length - 1] == 'number') {
timeout = spys.pop();
}
waitsFor(function() {
for (var i = 0; i < spys.length; ++i) {
if (spys[i].wasCalled) {
return true;
}
}
return false;
}, "Expecting callbacks to be called.", timeout);
}
| autotest/test-runner.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
if (window.sessionStorage != null) {
window.sessionStorage.clear();
}
// Timeout is 2 seconds to allow physical devices enough
// time to query the response. This is important for some
// Android devices.
var Tests = function() {};
Tests.TEST_TIMEOUT = 7500;
// Creates a spy that will fail if called.
function createDoNotCallSpy(name, opt_extraMessage) {
return jasmine.createSpy().andCallFake(function() {
var errorMessage = name + ' should not have been called.';
if (arguments.length) {
errorMessage += ' Got args: ' + JSON.stringify(arguments);
}
if (opt_extraMessage) {
errorMessage += '\n' + opt_extraMessage;
}
expect(false).toBe(true, errorMessage);
});
}
// Waits for any of the given spys to be called.
// Last param may be a custom timeout duration.
function waitsForAny() {
var spys = [].slice.call(arguments);
var timeout = Tests.TEST_TIMEOUT;
if (typeof spys[spys.length - 1] == 'number') {
timeout = spys.pop();
}
waitsFor(function() {
for (var i = 0; i < spys.length; ++i) {
if (spys[i].wasCalled) {
return true;
}
}
return false;
}, "Expecting callbacks to be called.", timeout);
}
| CB-6373: Make doNotCallSpies more resilient to errors
This ensures that they cause test failures, even when a JSON exception is thrown
while logging the error.
| autotest/test-runner.js | CB-6373: Make doNotCallSpies more resilient to errors | <ide><path>utotest/test-runner.js
<ide> // Creates a spy that will fail if called.
<ide> function createDoNotCallSpy(name, opt_extraMessage) {
<ide> return jasmine.createSpy().andCallFake(function() {
<del> var errorMessage = name + ' should not have been called.';
<del> if (arguments.length) {
<del> errorMessage += ' Got args: ' + JSON.stringify(arguments);
<del> }
<del> if (opt_extraMessage) {
<del> errorMessage += '\n' + opt_extraMessage;
<add> var errorMessage = "" + name + ' should not have been called.';
<add> try {
<add> if (arguments.length) {
<add> errorMessage += ' Got args: ' + JSON.stringify(arguments);
<add> }
<add> if (opt_extraMessage) {
<add> errorMessage += '\n' + opt_extraMessage;
<add> }
<add> } catch(e) {
<add> errorMessage += " (Cannot print details)";
<ide> }
<ide> expect(false).toBe(true, errorMessage);
<ide> }); |
|
Java | apache-2.0 | d399ab87fb3217ef4496499b0eac245ef814d0f3 | 0 | martinaas/cloudapp-mp2,martinaas/cloudapp-mp2,martinaas/cloudapp-mp2 | import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
import java.lang.Integer;
import java.util.StringTokenizer;
import java.util.TreeSet;
// >>> Don't Change
public class TopPopularLinks extends Configured implements Tool {
public static final Log LOG = LogFactory.getLog(TopPopularLinks.class);
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopPopularLinks(), args);
System.exit(res);
}
public static class IntArrayWritable extends ArrayWritable {
public IntArrayWritable() {
super(IntWritable.class);
}
public IntArrayWritable(Integer[] numbers) {
super(IntWritable.class);
IntWritable[] ints = new IntWritable[numbers.length];
for (int i = 0; i < numbers.length; i++) {
ints[i] = new IntWritable(numbers[i]);
}
set(ints);
}
}
// <<< Don't Change
@Override
public int run(String[] args) throws Exception {
Job job = Job.getInstance(this.getConf(), "Top Popular Links");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setMapperClass(LinkCountMap.class);
job.setReducerClass(LinkCountReduce.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(LinkCountMap.class);
return job.waitForCompletion(true) ? 0 : 1;
// Configuration conf = this.getConf();
// FileSystem fs = FileSystem.get(conf);
// Path tmpPath = new Path("/mp2/tmp");
// fs.delete(tmpPath, true);
//
// Job jobA = Job.getInstance(conf, "Links Count");
// jobA.setOutputKeyClass(IntWritable.class);
// jobA.setOutputValueClass(IntWritable.class);
//
// jobA.setMapperClass(LinkCountMap.class);
// jobA.setReducerClass(LinkCountReduce.class);
//
// FileInputFormat.setInputPaths(jobA, new Path(args[0]));
// FileOutputFormat.setOutputPath(jobA, tmpPath);
//
// jobA.setJarByClass(TopPopularLinks.class);
// jobA.waitForCompletion(true);
//
// Job jobB = Job.getInstance(conf, "Top Popular LinksT");
// jobB.setOutputKeyClass(IntWritable.class);
// jobB.setOutputValueClass(IntWritable.class);
//
// jobB.setMapOutputKeyClass(NullWritable.class);
// jobB.setMapOutputValueClass(IntArrayWritable.class);
//
// jobB.setMapperClass(TopLinksMap.class);
// jobB.setReducerClass(TopLinksReduce.class);
// jobB.setNumReduceTasks(1);
//
// FileInputFormat.setInputPaths(jobB, tmpPath);
// FileOutputFormat.setOutputPath(jobB, new Path(args[1]));
//
// jobB.setInputFormatClass(KeyValueTextInputFormat.class);
// jobB.setOutputFormatClass(TextOutputFormat.class);
//
// jobB.setJarByClass(TopPopularLinks.class);
// return jobB.waitForCompletion(true) ? 0 : 1;
}
public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> {
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer stringTokenizer1 = new StringTokenizer(line, ":");
String pageId = stringTokenizer1.nextToken();
context.write(new IntWritable(Integer.valueOf(pageId)), new IntWritable(0));
StringTokenizer stringTokenizer2 = new StringTokenizer(stringTokenizer1.nextToken(), ",");
while (stringTokenizer2.hasMoreTokens()) {
String nextToken = stringTokenizer2.nextToken();
context.write(new IntWritable(Integer.valueOf(nextToken)), new IntWritable(1));
}
}
}
public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
@Override
public void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
// public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> {
// Integer N;
// private TreeSet<Pair<Integer, Integer>> topLinksMap =
// new TreeSet<Pair<Integer, Integer>>();
//
// @Override
// protected void setup(Context context) throws IOException,InterruptedException {
// Configuration conf = context.getConfiguration();
// this.N = conf.getInt("N", 10);
// }
//
// @Override
// public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
// Integer count = Integer.parseInt(value.toString());
// Integer pageId = Integer.parseInt(key.toString());
// topLinksMap.add(new Pair<Integer, Integer>(count,
// pageId));
// if (topLinksMap.size() > N) {
// topLinksMap.remove(topLinksMap.first());
// }
// }
//
// @Override
// protected void cleanup(Context context) throws IOException, InterruptedException {
// for (Pair<Integer, Integer> item : topLinksMap) {
// Integer[] integers = {item.second,
// item.first};
// IntArrayWritable val = new
// IntArrayWritable(integers);
// context.write(NullWritable.get(), val);
// }
// }
// }
//
// public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> {
// Integer N;
// private TreeSet<Pair<Integer, Integer>> countToLinksMap =
// new TreeSet<Pair<Integer, Integer>>();
//
// @Override
// protected void setup(Context context) throws IOException,InterruptedException {
// Configuration conf = context.getConfiguration();
// this.N = conf.getInt("N", 10);
// }
//
// @Override
// public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context context) throws IOException, InterruptedException {
// for (IntArrayWritable val: values) {
// IntWritable[] pair= (IntWritable[]) val.toArray();
// Integer pageId = Integer.parseInt(pair[0].toString());
// Integer count =
// Integer.parseInt(pair[1].toString());
// countToLinksMap.add(new Pair<Integer,
// Integer>(count, pageId));
// if (countToLinksMap.size() > N) {
//
// countToLinksMap.remove(countToLinksMap.first());
// }
// }
// for (Pair<Integer, Integer> item: countToLinksMap) {
// IntWritable id = new IntWritable(item.second);
// IntWritable value = new IntWritable(item.first);
// context.write(id, value);
// }
// }
// }
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change | TopPopularLinks.java | import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
import java.lang.Integer;
import java.util.StringTokenizer;
import java.util.TreeSet;
// >>> Don't Change
public class TopPopularLinks extends Configured implements Tool {
public static final Log LOG = LogFactory.getLog(TopPopularLinks.class);
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopPopularLinks(), args);
System.exit(res);
}
public static class IntArrayWritable extends ArrayWritable {
public IntArrayWritable() {
super(IntWritable.class);
}
public IntArrayWritable(Integer[] numbers) {
super(IntWritable.class);
IntWritable[] ints = new IntWritable[numbers.length];
for (int i = 0; i < numbers.length; i++) {
ints[i] = new IntWritable(numbers[i]);
}
set(ints);
}
}
// <<< Don't Change
@Override
public int run(String[] args) throws Exception {
Job job = Job.getInstance(this.getConf(), "Top Popular Links");
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(IntWritable.class);
job.setMapperClass(LinkCountMap.class);
job.setReducerClass(LinkCountReduce.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(LinkCountMap.class);
return job.waitForCompletion(true) ? 0 : 1;
// Configuration conf = this.getConf();
// FileSystem fs = FileSystem.get(conf);
// Path tmpPath = new Path("/mp2/tmp");
// fs.delete(tmpPath, true);
//
// Job jobA = Job.getInstance(conf, "Links Count");
// jobA.setOutputKeyClass(IntWritable.class);
// jobA.setOutputValueClass(IntWritable.class);
//
// jobA.setMapperClass(LinkCountMap.class);
// jobA.setReducerClass(LinkCountReduce.class);
//
// FileInputFormat.setInputPaths(jobA, new Path(args[0]));
// FileOutputFormat.setOutputPath(jobA, tmpPath);
//
// jobA.setJarByClass(TopPopularLinks.class);
// jobA.waitForCompletion(true);
//
// Job jobB = Job.getInstance(conf, "Top Popular LinksT");
// jobB.setOutputKeyClass(IntWritable.class);
// jobB.setOutputValueClass(IntWritable.class);
//
// jobB.setMapOutputKeyClass(NullWritable.class);
// jobB.setMapOutputValueClass(IntArrayWritable.class);
//
// jobB.setMapperClass(TopLinksMap.class);
// jobB.setReducerClass(TopLinksReduce.class);
// jobB.setNumReduceTasks(1);
//
// FileInputFormat.setInputPaths(jobB, tmpPath);
// FileOutputFormat.setOutputPath(jobB, new Path(args[1]));
//
// jobB.setInputFormatClass(KeyValueTextInputFormat.class);
// jobB.setOutputFormatClass(TextOutputFormat.class);
//
// jobB.setJarByClass(TopPopularLinks.class);
// return jobB.waitForCompletion(true) ? 0 : 1;
}
public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> {
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer stringTokenizer = new StringTokenizer(line, ":");
StringTokenizer linksTokenizer = new StringTokenizer(stringTokenizer.nextToken(), " ");
while (linksTokenizer.hasMoreTokens()) {
String nextToken = linksTokenizer.nextToken();
context.write(new IntWritable(Integer.valueOf(nextToken)), new IntWritable(1));
}
}
}
public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
@Override
public void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
if (sum > 0) {
context.write(key, new IntWritable(sum));
}
}
}
// public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> {
// Integer N;
// private TreeSet<Pair<Integer, Integer>> topLinksMap =
// new TreeSet<Pair<Integer, Integer>>();
//
// @Override
// protected void setup(Context context) throws IOException,InterruptedException {
// Configuration conf = context.getConfiguration();
// this.N = conf.getInt("N", 10);
// }
//
// @Override
// public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
// Integer count = Integer.parseInt(value.toString());
// Integer pageId = Integer.parseInt(key.toString());
// topLinksMap.add(new Pair<Integer, Integer>(count,
// pageId));
// if (topLinksMap.size() > N) {
// topLinksMap.remove(topLinksMap.first());
// }
// }
//
// @Override
// protected void cleanup(Context context) throws IOException, InterruptedException {
// for (Pair<Integer, Integer> item : topLinksMap) {
// Integer[] integers = {item.second,
// item.first};
// IntArrayWritable val = new
// IntArrayWritable(integers);
// context.write(NullWritable.get(), val);
// }
// }
// }
//
// public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> {
// Integer N;
// private TreeSet<Pair<Integer, Integer>> countToLinksMap =
// new TreeSet<Pair<Integer, Integer>>();
//
// @Override
// protected void setup(Context context) throws IOException,InterruptedException {
// Configuration conf = context.getConfiguration();
// this.N = conf.getInt("N", 10);
// }
//
// @Override
// public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context context) throws IOException, InterruptedException {
// for (IntArrayWritable val: values) {
// IntWritable[] pair= (IntWritable[]) val.toArray();
// Integer pageId = Integer.parseInt(pair[0].toString());
// Integer count =
// Integer.parseInt(pair[1].toString());
// countToLinksMap.add(new Pair<Integer,
// Integer>(count, pageId));
// if (countToLinksMap.size() > N) {
//
// countToLinksMap.remove(countToLinksMap.first());
// }
// }
// for (Pair<Integer, Integer> item: countToLinksMap) {
// IntWritable id = new IntWritable(item.second);
// IntWritable value = new IntWritable(item.first);
// context.write(id, value);
// }
// }
// }
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change | Commit
| TopPopularLinks.java | Commit | <ide><path>opPopularLinks.java
<ide> @Override
<ide> public int run(String[] args) throws Exception {
<ide> Job job = Job.getInstance(this.getConf(), "Top Popular Links");
<del> job.setOutputKeyClass(IntWritable.class);
<add> job.setOutputKeyClass(Text.class);
<ide> job.setOutputValueClass(IntWritable.class);
<ide>
<del> job.setMapOutputKeyClass(IntWritable.class);
<add> job.setMapOutputKeyClass(Text.class);
<ide> job.setMapOutputValueClass(IntWritable.class);
<ide>
<ide> job.setMapperClass(LinkCountMap.class);
<ide> @Override
<ide> public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
<ide> String line = value.toString();
<del> StringTokenizer stringTokenizer = new StringTokenizer(line, ":");
<del> StringTokenizer linksTokenizer = new StringTokenizer(stringTokenizer.nextToken(), " ");
<del> while (linksTokenizer.hasMoreTokens()) {
<del> String nextToken = linksTokenizer.nextToken();
<add> StringTokenizer stringTokenizer1 = new StringTokenizer(line, ":");
<add> String pageId = stringTokenizer1.nextToken();
<add> context.write(new IntWritable(Integer.valueOf(pageId)), new IntWritable(0));
<add> StringTokenizer stringTokenizer2 = new StringTokenizer(stringTokenizer1.nextToken(), ",");
<add> while (stringTokenizer2.hasMoreTokens()) {
<add> String nextToken = stringTokenizer2.nextToken();
<ide> context.write(new IntWritable(Integer.valueOf(nextToken)), new IntWritable(1));
<ide> }
<ide> }
<ide> for (IntWritable val : values) {
<ide> sum += val.get();
<ide> }
<del> if (sum > 0) {
<del> context.write(key, new IntWritable(sum));
<del> }
<add> context.write(key, new IntWritable(sum));
<ide> }
<ide> }
<ide> |
|
Java | agpl-3.0 | de22d2b3eb4bb7a6f6659ae550e75280f4832cba | 0 | ronancpl/MapleSolaxiaV2,ronancpl/MapleSolaxiaV2 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.te
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client.command;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import net.MaplePacketHandler;
import net.PacketProcessor;
import net.server.Server;
import net.server.channel.Channel;
import net.server.world.World;
import provider.MapleData;
import provider.MapleDataProvider;
import provider.MapleDataProviderFactory;
import provider.MapleDataTool;
import scripting.npc.NPCScriptManager;
import scripting.portal.PortalScriptManager;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MaplePortal;
import server.MapleShopFactory;
import server.TimerManager;
import server.events.gm.MapleEvent;
import server.expeditions.MapleExpedition;
import server.gachapon.MapleGachapon.Gachapon;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleMonsterInformationProvider;
import server.life.MapleNPC;
import server.life.MonsterDropEntry;
import server.maps.MapleMap;
import server.maps.MapleMapItem;
import server.maps.MapleMapObject;
import server.maps.MapleMapObjectType;
import server.quest.MapleQuest;
import tools.DatabaseConnection;
import tools.FilePrinter;
import tools.HexTool;
import tools.MapleLogger;
import tools.MaplePacketCreator;
import tools.Pair;
import tools.Randomizer;
import tools.data.input.ByteArrayByteStream;
import tools.data.input.GenericSeekableLittleEndianAccessor;
import tools.data.input.SeekableLittleEndianAccessor;
import tools.data.output.MaplePacketLittleEndianWriter;
import client.MapleBuffStat;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleJob;
import client.MapleStat;
import client.Skill;
import client.SkillFactory;
import client.inventory.Item;
import client.inventory.MapleInventoryType;
import client.inventory.MaplePet;
import constants.GameConstants;
import constants.ItemConstants;
import constants.ServerConstants;
import java.util.ArrayList;
import server.maps.FieldLimit;
public class Commands {
private static HashMap<String, Integer> gotomaps = new HashMap<String, Integer>();
private static String[] tips = {
"Please only use @gm in emergencies or to report somebody.",
"To report a bug or make a suggestion, use the forum.",
"Please do not use @gm to ask if a GM is online.",
"Do not ask if you can receive help, just state your issue.",
"Do not say 'I have a bug to report', just state it.",
};
private static String[] songs = {
"Jukebox/Congratulation",
"Bgm00/SleepyWood",
"Bgm00/FloralLife",
"Bgm00/GoPicnic",
"Bgm00/Nightmare",
"Bgm00/RestNPeace",
"Bgm01/AncientMove",
"Bgm01/MoonlightShadow",
"Bgm01/WhereTheBarlogFrom",
"Bgm01/CavaBien",
"Bgm01/HighlandStar",
"Bgm01/BadGuys",
"Bgm02/MissingYou",
"Bgm02/WhenTheMorningComes",
"Bgm02/EvilEyes",
"Bgm02/JungleBook",
"Bgm02/AboveTheTreetops",
"Bgm03/Subway",
"Bgm03/Elfwood",
"Bgm03/BlueSky",
"Bgm03/Beachway",
"Bgm03/SnowyVillage",
"Bgm04/PlayWithMe",
"Bgm04/WhiteChristmas",
"Bgm04/UponTheSky",
"Bgm04/ArabPirate",
"Bgm04/Shinin'Harbor",
"Bgm04/WarmRegard",
"Bgm05/WolfWood",
"Bgm05/DownToTheCave",
"Bgm05/AbandonedMine",
"Bgm05/MineQuest",
"Bgm05/HellGate",
"Bgm06/FinalFight",
"Bgm06/WelcomeToTheHell",
"Bgm06/ComeWithMe",
"Bgm06/FlyingInABlueDream",
"Bgm06/FantasticThinking",
"Bgm07/WaltzForWork",
"Bgm07/WhereverYouAre",
"Bgm07/FunnyTimeMaker",
"Bgm07/HighEnough",
"Bgm07/Fantasia",
"Bgm08/LetsMarch",
"Bgm08/ForTheGlory",
"Bgm08/FindingForest",
"Bgm08/LetsHuntAliens",
"Bgm08/PlotOfPixie",
"Bgm09/DarkShadow",
"Bgm09/TheyMenacingYou",
"Bgm09/FairyTale",
"Bgm09/FairyTalediffvers",
"Bgm09/TimeAttack",
"Bgm10/Timeless",
"Bgm10/TimelessB",
"Bgm10/BizarreTales",
"Bgm10/TheWayGrotesque",
"Bgm10/Eregos",
"Bgm11/BlueWorld",
"Bgm11/Aquarium",
"Bgm11/ShiningSea",
"Bgm11/DownTown",
"Bgm11/DarkMountain",
"Bgm12/AquaCave",
"Bgm12/DeepSee",
"Bgm12/WaterWay",
"Bgm12/AcientRemain",
"Bgm12/RuinCastle",
"Bgm12/Dispute",
"Bgm13/CokeTown",
"Bgm13/Leafre",
"Bgm13/Minar'sDream",
"Bgm13/AcientForest",
"Bgm13/TowerOfGoddess",
"Bgm14/DragonLoad",
"Bgm14/HonTale",
"Bgm14/CaveOfHontale",
"Bgm14/DragonNest",
"Bgm14/Ariant",
"Bgm14/HotDesert",
"Bgm15/MureungHill",
"Bgm15/MureungForest",
"Bgm15/WhiteHerb",
"Bgm15/Pirate",
"Bgm15/SunsetDesert",
"Bgm16/Duskofgod",
"Bgm16/FightingPinkBeen",
"Bgm16/Forgetfulness",
"Bgm16/Remembrance",
"Bgm16/Repentance",
"Bgm16/TimeTemple",
"Bgm17/MureungSchool1",
"Bgm17/MureungSchool2",
"Bgm17/MureungSchool3",
"Bgm17/MureungSchool4",
"Bgm18/BlackWing",
"Bgm18/DrillHall",
"Bgm18/QueensGarden",
"Bgm18/RaindropFlower",
"Bgm18/WolfAndSheep",
"Bgm19/BambooGym",
"Bgm19/CrystalCave",
"Bgm19/MushCatle",
"Bgm19/RienVillage",
"Bgm19/SnowDrop",
"Bgm20/GhostShip",
"Bgm20/NetsPiramid",
"Bgm20/UnderSubway",
"Bgm21/2021year",
"Bgm21/2099year",
"Bgm21/2215year",
"Bgm21/2230year",
"Bgm21/2503year",
"Bgm21/KerningSquare",
"Bgm21/KerningSquareField",
"Bgm21/KerningSquareSubway",
"Bgm21/TeraForest",
"BgmEvent/FunnyRabbit",
"BgmEvent/FunnyRabbitFaster",
"BgmEvent/wedding",
"BgmEvent/weddingDance",
"BgmEvent/wichTower",
"BgmGL/amoria",
"BgmGL/Amorianchallenge",
"BgmGL/chapel",
"BgmGL/cathedral",
"BgmGL/Courtyard",
"BgmGL/CrimsonwoodKeep",
"BgmGL/CrimsonwoodKeepInterior",
"BgmGL/GrandmastersGauntlet",
"BgmGL/HauntedHouse",
"BgmGL/NLChunt",
"BgmGL/NLCtown",
"BgmGL/NLCupbeat",
"BgmGL/PartyQuestGL",
"BgmGL/PhantomForest",
"BgmJp/Feeling",
"BgmJp/BizarreForest",
"BgmJp/Hana",
"BgmJp/Yume",
"BgmJp/Bathroom",
"BgmJp/BattleField",
"BgmJp/FirstStepMaster",
"BgmMY/Highland",
"BgmMY/KualaLumpur",
"BgmSG/BoatQuay_field",
"BgmSG/BoatQuay_town",
"BgmSG/CBD_field",
"BgmSG/CBD_town",
"BgmSG/Ghostship",
"BgmUI/ShopBgm",
"BgmUI/Title"
};
static {
gotomaps.put("gmmap", 180000000);
gotomaps.put("southperry", 60000);
gotomaps.put("amherst", 1010000);
gotomaps.put("henesys", 100000000);
gotomaps.put("ellinia", 101000000);
gotomaps.put("perion", 102000000);
gotomaps.put("kerning", 103000000);
gotomaps.put("lith", 104000000);
gotomaps.put("sleepywood", 105040300);
gotomaps.put("florina", 110000000);
gotomaps.put("orbis", 200000000);
gotomaps.put("happy", 209000000);
gotomaps.put("elnath", 211000000);
gotomaps.put("ludi", 220000000);
gotomaps.put("aqua", 230000000);
gotomaps.put("leafre", 240000000);
gotomaps.put("mulung", 250000000);
gotomaps.put("herb", 251000000);
gotomaps.put("omega", 221000000);
gotomaps.put("korean", 222000000);
gotomaps.put("nlc", 600000000);
gotomaps.put("excavation", 990000000);
gotomaps.put("pianus", 230040420);
gotomaps.put("horntail", 240060200);
gotomaps.put("mushmom", 100000005);
gotomaps.put("griffey", 240020101);
gotomaps.put("manon", 240020401);
gotomaps.put("horseman", 682000001);
gotomaps.put("balrog", 105090900);
gotomaps.put("zakum", 211042300);
gotomaps.put("papu", 220080001);
gotomaps.put("showa", 801000000);
gotomaps.put("guild", 200000301);
gotomaps.put("shrine", 800000000);
gotomaps.put("skelegon", 240040511);
gotomaps.put("hpq", 100000200);
gotomaps.put("ht", 240050400);
gotomaps.put("fm", 910000000);
}
public static boolean executePlayerCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
if (heading == '!' && player.gmLevel() == 0) {
player.yellowMessage("You may not use !" + sub[0] + ", please try /" + sub[0]);
return false;
}
switch (sub[0]) {
case "help":
case "commands":
player.yellowMessage("After you vote, talk to Rooney to get a leaf and redeem it for prizes!");
player.message("@dispose: Fixes your character if it is stuck.");
player.message("@online: Displays a list of all online players.");
player.message("@time: Displays the current server time.");
player.message("@rates: Displays your current DROP, MESO and EXP rates.");
player.message("@points: Tells you how many unused vote points you have and when/if you can vote.");
player.message("@gm <message>: Sends a message to all online GMs in the case of an emergency.");
player.message("@bug <bug>: Sends a bug report to all developers.");
player.message("@joinevent: If an event is in progress, use this to warp to the event map.");
player.message("@leaveevent: If an event has ended, use this to warp to your original map.");
player.message("@staff: Lists the staff of Solaxia.");
player.message("@uptime: Shows how long Solaxia has been online.");
player.message("@whatdropsfrom <monster name>: Displays a list of drops and chances for a specified monster.");
player.message("@whodrops <item name>: Displays monsters that drop an item given an item name.");
player.message("@uptime: Shows how long Solaxia has been online.");
player.message("@bosshp: Displays the remaining HP of the bosses on your map.");
if(ServerConstants.USE_DEBUG) {
player.message("@debugpos: Displays the coordinates on the map the player is currently located.");
player.message("@debugmap: Displays info about the current map the player is located.");
player.message("@debugevent: Displays the name of the event in which the player is currently registered.");
player.message("@debugreactors: Displays current info for all reactors on the map the the player is currently located.");
}
break;
case "time":
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
player.yellowMessage("Solaxia Server Time: " + dateFormat.format(new Date()));
break;
case "staff":
player.yellowMessage("MapleSolaxia Staff");
player.yellowMessage("Aria - Administrator");
player.yellowMessage("Twdtwd - Administrator");
player.yellowMessage("Exorcist - Developer");
player.yellowMessage("SharpAceX - Developer");
player.yellowMessage("Zygon - Freelance Developer");
player.yellowMessage("SourMjolk - Game Master");
player.yellowMessage("Kanade - Game Master");
player.yellowMessage("Kitsune - Game Master");
player.yellowMessage("Branch Staff");
player.yellowMessage("Ronan - Freelance Developer");
break;
case "lastrestart":
case "uptime":
long milliseconds = System.currentTimeMillis() - Server.uptime;
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
int days = (int) ((milliseconds / (1000*60*60*24)));
player.yellowMessage("Solaxia has been online for " + days + " days " + hours + " hours " + minutes + " minutes and " + seconds + " seconds.");
break;
case "gacha":
if (player.gmLevel() == 0) { // Sigh, need it for now...
player.yellowMessage("Player Command " + heading + sub[0] + " does not exist, see @help for a list of commands.");
return false;
}
Gachapon gacha = null;
String search = joinStringFrom(sub, 1);
String gachaName = "";
String [] names = {"Henesys", "Ellinia", "Perion", "Kerning City", "Sleepywood", "Mushroom Shrine", "Showa Spa Male", "Showa Spa Female", "New Leaf City", "Nautilus Harbor"};
int [] ids = {9100100, 9100101, 9100102, 9100103, 9100104, 9100105, 9100106, 9100107, 9100109, 9100117};
for (int i = 0; i < names.length; i++){
if (search.equalsIgnoreCase(names[i])){
gachaName = names[i];
gacha = Gachapon.getByNpcId(ids[i]);
}
}
if (gacha == null){
player.yellowMessage("Please use @gacha <name> where name corresponds to one of the below:");
for (String name : names){
player.yellowMessage(name);
}
break;
}
String output = "The #b" + gachaName + "#k Gachapon contains the following items.\r\n\r\n";
for (int i = 0; i < 2; i++){
for (int id : gacha.getItems(i)){
output += "-" + MapleItemInformationProvider.getInstance().getName(id) + "\r\n";
}
}
output += "\r\nPlease keep in mind that there are items that are in all gachapons and are not listed here.";
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "whatdropsfrom":
if (sub.length < 2) {
player.dropMessage(5, "Please do @whatdropsfrom <monster name>");
break;
}
String monsterName = joinStringFrom(sub, 1);
output = "";
int limit = 3;
Iterator<Pair<Integer, String>> listIterator = MapleMonsterInformationProvider.getMobsIDsFromName(monsterName).iterator();
for (int i = 0; i < limit; i++) {
if(listIterator.hasNext()) {
Pair<Integer, String> data = listIterator.next();
int mobId = data.getLeft();
String mobName = data.getRight();
output += mobName + " drops the following items:\r\n\r\n";
for (MonsterDropEntry drop : MapleMonsterInformationProvider.getInstance().retrieveDrop(mobId)){
try {
String name = MapleItemInformationProvider.getInstance().getName(drop.itemId);
if (name.equals("null") || drop.chance == 0){
continue;
}
float chance = 1000000 / drop.chance / player.getDropRate();
output += "- " + name + " (1/" + (int) chance + ")\r\n";
} catch (Exception ex){
ex.printStackTrace();
continue;
}
}
output += "\r\n";
}
}
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "whodrops":
if (sub.length < 2) {
player.dropMessage(5, "Please do @whodrops <item name>");
break;
}
String searchString = joinStringFrom(sub, 1);
output = "";
listIterator = MapleItemInformationProvider.getInstance().getItemDataByName(searchString).iterator();
if(listIterator.hasNext()) {
int count = 1;
while(listIterator.hasNext() && count <= 3) {
Pair<Integer, String> data = listIterator.next();
output += "#b" + data.getRight() + "#k is dropped by:\r\n";
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM drop_data WHERE itemid = ? LIMIT 50");
ps.setInt(1, data.getLeft());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String resultName = MapleMonsterInformationProvider.getMobNameFromID(rs.getInt("dropperid"));
if (resultName != null) {
output += resultName + ", ";
}
}
rs.close();
ps.close();
} catch (Exception e) {
player.dropMessage("There was a problem retreiving the required data. Please try again.");
e.printStackTrace();
return true;
}
output += "\r\n\r\n";
count++;
}
} else {
player.dropMessage(5, "The item you searched for doesn't exist.");
break;
}
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "dispose":
NPCScriptManager.getInstance().dispose(c);
c.announce(MaplePacketCreator.enableActions());
c.removeClickedNPC();
player.message("You've been disposed.");
break;
case "rates":
c.resetVoteTime();
player.yellowMessage("DROP RATE");
player.message(">>Base DROP Rate: " + c.getWorldServer().getDropRate() + "x");
player.message(">>Your DROP Rate: " + player.getDropRate() / c.getWorldServer().getDropRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total DROP Rate: " + player.getDropRate() + "x");
player.yellowMessage("MESO RATE");
player.message(">>Base MESO Rate: " + c.getWorldServer().getMesoRate() + "x");
player.message(">>Your MESO Rate: " + player.getMesoRate() / c.getWorldServer().getMesoRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total MESO Rate: " + player.getMesoRate() + "x");
player.yellowMessage("EXP RATE");
player.message(">>Base EXP Rate: " + c.getWorldServer().getExpRate() + "x");
player.message(">>Your EXP Rate: " + player.getExpRate() / c.getWorldServer().getExpRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total EXP Rate: " + player.getExpRate() + "x");
/*if(c.getWorldServer().getExpRate() > ServerConstants.EXP_RATE) {
player.message(">>Event EXP bonus: " + (c.getWorldServer().getExpRate() - ServerConstants.EXP_RATE) + "x");
}
player.message(">>Voted EXP bonus: " + (c.hasVotedAlready() ? "1x" : "0x (If you vote now, you will earn an additional 1x EXP!)"));
if (player.getLevel() < 10) {
player.message("Players under level 10 always have 1x exp.");
}*/
break;
case "online":
for (Channel ch : Server.getInstance().getChannelsFromWorld(player.getWorld())) {
player.yellowMessage("Players in Channel " + ch.getId() + ":");
for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
if (!chr.isGM()) {
player.message(" >> " + MapleCharacter.makeMapleReadable(chr.getName()) + " is at " + chr.getMap().getMapName() + ".");
}
}
}
break;
case "gm":
if (sub.length < 3) { // #goodbye 'hi'
player.dropMessage(5, "Your message was too short. Please provide as much detail as possible.");
break;
}
String message = joinStringFrom(sub, 1);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.sendYellowTip("[GM MESSAGE]:" + MapleCharacter.makeMapleReadable(player.getName()) + ": " + message));
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(1, message));
FilePrinter.printError("gm.txt", MapleCharacter.makeMapleReadable(player.getName()) + ": " + message + "\r\n");
player.dropMessage(5, "Your message '" + message + "' was sent to GMs.");
player.dropMessage(5, tips[Randomizer.nextInt(tips.length)]);
break;
case "bug":
if (sub.length < 2) {
player.dropMessage(5, "Message too short and not sent. Please do @bug <bug>");
break;
}
message = joinStringFrom(sub, 1);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.sendYellowTip("[BUG]:" + MapleCharacter.makeMapleReadable(player.getName()) + ": " + message));
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(1, message));
FilePrinter.printError("bug.txt", MapleCharacter.makeMapleReadable(player.getName()) + ": " + message + "\r\n");
player.dropMessage(5, "Your bug '" + message + "' was submitted successfully to our developers. Thank you!");
break;
/*
case "points":
player.dropMessage(5, "You have " + c.getVotePoints() + " vote point(s).");
if (c.hasVotedAlready()) {
Date currentDate = new Date();
int time = (int) ((int) 86400 - ((currentDate.getTime() / 1000) - c.getVoteTime())); //ugly as fuck
hours = time / 3600;
minutes = time % 3600 / 60;
seconds = time % 3600 % 60;
player.yellowMessage("You have already voted. You can vote again in " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
} else {
player.yellowMessage("You are free to vote! Make sure to vote to gain a vote point!");
}
break;
*/
case "joinevent":
case "event":
case "join":
if(!FieldLimit.CHANGECHANNEL.check(player.getMap().getFieldLimit())) {
MapleEvent event = c.getChannelServer().getEvent();
if(event != null) {
if(event.getMapId() != player.getMapId()) {
if(event.getLimit() > 0) {
player.saveLocation("EVENT");
if(event.getMapId() == 109080000 || event.getMapId() == 109060001)
player.setTeam(event.getLimit() % 2);
event.minusLimit();
player.changeMap(event.getMapId());
} else {
player.dropMessage("The limit of players for the event has already been reached.");
}
} else {
player.dropMessage(5, "You are already in the event.");
}
} else {
player.dropMessage(5, "There is currently no event in progress.");
}
} else {
player.dropMessage(5, "You are currently in a map where you can't join an event.");
}
break;
case "leaveevent":
case "leave":
int returnMap = player.getSavedLocation("EVENT");
if(returnMap != -1) {
if(player.getOla() != null) {
player.getOla().resetTimes();
player.setOla(null);
}
if(player.getFitness() != null) {
player.getFitness().resetTimes();
player.setFitness(null);
}
player.changeMap(returnMap);
if(c.getChannelServer().getEvent() != null) {
c.getChannelServer().getEvent().addLimit();
}
} else {
player.dropMessage(5, "You are not currently in an event.");
}
break;
case "bosshp":
for(MapleMonster monster : player.getMap().getMonsters()) {
if(monster != null && monster.isBoss() && monster.getHp() > 0) {
long percent = monster.getHp() * 100L / monster.getMaxHp();
String bar = "[";
for (int i = 0; i < 100; i++){
bar += i < percent ? "|" : ".";
}
bar += "]";
player.yellowMessage(monster.getName() + " has " + percent + "% HP left.");
player.yellowMessage("HP: " + bar);
}
}
break;
case "ranks":
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = DatabaseConnection.getConnection().prepareStatement("SELECT `characters`.`name`, `characters`.`level` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` = '0' AND `accounts`.`banned` = '0' ORDER BY level DESC, exp DESC LIMIT 50");
rs = ps.executeQuery();
player.announce(MaplePacketCreator.showPlayerRanks(9010000, rs));
ps.close();
rs.close();
} catch(SQLException ex) {
ex.printStackTrace();
} finally {
try {
if(ps != null && !ps.isClosed()) {
ps.close();
}
if(rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
break;
//debug only
case "debugpos":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current map position: (" + player.getPosition().getX() + ", " + player.getPosition().getY() + ").");
}
break;
case "debugmap":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current map id " + player.getMap().getId() + ", event: '" + ((player.getMap().getEventInstance() != null) ? player.getMap().getEventInstance().getName() : "null") + "'; Players: " + player.getMap().getAllPlayers().size() + ", Mobs: " + player.getMap().countMonsters() + ", Reactors: " + player.getMap().countReactors() + ".");
}
break;
case "debugevent":
if(ServerConstants.USE_DEBUG) {
if(player.getEventInstance() == null) player.dropMessage("Player currently not in an event.");
else player.dropMessage("Current event name: " + player.getEventInstance().getName() + ".");
}
break;
case "debugreactors":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current reactor states on map " + player.getMapId() + ":");
for(Pair p: player.getMap().reportReactorStates()) {
player.dropMessage("Reactor id: " + p.getLeft() + " -> State: " + p.getRight() + ".");
}
}
break;
default:
if (player.gmLevel() == 0) {
player.yellowMessage("Player Command " + heading + sub[0] + " does not exist, see @help for a list of commands.");
}
return false;
}
return true;
}
public static boolean executeGMCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
Channel cserv = c.getChannelServer();
Server srv = Server.getInstance();
if (sub[0].equals("ap")) {
if (sub.length < 3) {
player.setRemainingAp(Integer.parseInt(sub[1]));
player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
} else {
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.setRemainingAp(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.AVAILABLEAP, victim.getRemainingAp());
}
} else if (sub[0].equals("buffme")) {
final int[] array = {9001000, 9101002, 9101003, 9101008, 2001002, 1101007, 1005, 2301003, 5121009, 1111002, 4111001, 4111002, 4211003, 4211005, 1321000, 2321004, 3121002};
for (int i : array) {
SkillFactory.getSkill(i).getEffect(SkillFactory.getSkill(i).getMaxLevel()).applyTo(player);
}
} else if (sub[0].equals("spawn")) {
if (sub.length < 2) {
player.yellowMessage("Syntax: !spawn <mobid>");
return false;
}
MapleMonster monster = MapleLifeFactory.getMonster(Integer.parseInt(sub[1]));
if (monster == null) {
return true;
}
if (sub.length > 2) {
for (int i = 0; i < Integer.parseInt(sub[2]); i++) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
}
} else {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
}
} else if (sub[0].equals("bomb")) {
if (sub.length > 1){
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), victim.getPosition());
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !bomb on " + victim.getName()));
} else {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), player.getPosition());
}
} else if (sub[0].equals("mutemap")) {
if(player.getMap().isMuted()) {
player.getMap().setMuted(false);
player.dropMessage(5, "The map you are in has been un-muted.");
} else {
player.getMap().setMuted(true);
player.dropMessage(5, "The map you are in has been muted.");
}
} else if (sub[0].equals("checkdmg")) {
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
int maxBase = victim.calculateMaxBaseDamage(victim.getTotalWatk());
Integer watkBuff = victim.getBuffedValue(MapleBuffStat.WATK);
Integer matkBuff = victim.getBuffedValue(MapleBuffStat.MATK);
Integer blessing = victim.getSkillLevel(10000000 * player.getJobType() + 12);
if(watkBuff == null) watkBuff = 0;
if(matkBuff == null) matkBuff = 0;
player.dropMessage(5, "Cur Str: " + victim.getTotalStr() + " Cur Dex: " + victim.getTotalDex() + " Cur Int: " + victim.getTotalInt() + " Cur Luk: " + victim.getTotalLuk());
player.dropMessage(5, "Cur WATK: " + victim.getTotalWatk() + " Cur MATK: " + victim.getTotalMagic());
player.dropMessage(5, "Cur WATK Buff: " + watkBuff + " Cur MATK Buff: " + matkBuff + " Cur Blessing Level: " + blessing);
player.dropMessage(5, victim.getName() + "'s maximum base damage (before skills) is " + maxBase);
} else if (sub[0].equals("inmap")) {
String s = "";
for (MapleCharacter chr : player.getMap().getCharacters()) {
s += chr.getName() + " ";
}
player.message(s);
} else if (sub[0].equals("cleardrops")) {
player.getMap().clearDrops(player);
} else if (sub[0].equals("go")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !spawn <mobid>");
return false;
}
if (gotomaps.containsKey(sub[1])) {
MapleMap target = c.getChannelServer().getMapFactory().getMap(gotomaps.get(sub[1]));
MaplePortal targetPortal = target.getPortal(0);
if (player.getEventInstance() != null) {
player.getEventInstance().removePlayer(player);
}
player.changeMap(target, targetPortal);
} else {
player.dropMessage(5, "That map does not exist.");
}
} else if (sub[0].equals("reloadevents")) {
for (Channel ch : Server.getInstance().getAllChannels()) {
ch.reloadEventScriptManager();
}
player.dropMessage(5, "Reloaded Events");
} else if (sub[0].equals("reloaddrops")) {
MapleMonsterInformationProvider.getInstance().clearDrops();
player.dropMessage(5, "Reloaded Drops");
} else if (sub[0].equals("reloadportals")) {
PortalScriptManager.getInstance().reloadPortalScripts();
player.dropMessage(5, "Reloaded Portals");
} else if (sub[0].equals("whereami")) { //This is so not going to work on the first commit
player.yellowMessage("Map ID: " + player.getMap().getId());
player.yellowMessage("Players on this map:");
for (MapleMapObject mmo : player.getMap().getAllPlayer()) {
MapleCharacter chr = (MapleCharacter) mmo;
player.dropMessage(5, ">> " + chr.getName());
}
player.yellowMessage("NPCs on this map:");
for (MapleMapObject npcs : player.getMap().getMapObjects()) {
if (npcs instanceof MapleNPC) {
MapleNPC npc = (MapleNPC) npcs;
player.dropMessage(5, ">> " + npc.getName() + " - " + npc.getId());
}
}
player.yellowMessage("Monsters on this map:");
for (MapleMapObject mobs : player.getMap().getMapObjects()) {
if (mobs instanceof MapleMonster) {
MapleMonster mob = (MapleMonster) mobs;
if(mob.isAlive()){
player.dropMessage(5, ">> " + mob.getName() + " - " + mob.getId());
}
}
}
} else if (sub[0].equals("warp")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !warp <mapid>");
return false;
}
try {
MapleMap target = c.getChannelServer().getMapFactory().getMap(Integer.parseInt(sub[1]));
if (target == null) {
player.yellowMessage("Map ID " + sub[1] + " is invalid.");
return false;
}
if (player.getEventInstance() != null) {
player.getEventInstance().removePlayer(player);
}
player.changeMap(target, target.getPortal(0));
} catch (Exception ex) {
ex.printStackTrace();
player.yellowMessage("Map ID " + sub[1] + " is invalid.");
return false;
}
} else if (sub[0].equals("reloadmap")) {
MapleMap oldMap = c.getPlayer().getMap();
MapleMap newMap = c.getChannelServer().getMapFactory().getMap(player.getMapId());
for (MapleCharacter ch : oldMap.getCharacters()) {
ch.changeMap(newMap);
}
oldMap = null;
newMap.respawn();
} else if (sub[0].equals("music")){
if (sub.length < 2) {
player.yellowMessage("Syntax: !music <song>");
for (String s : songs){
player.yellowMessage(s);
}
return false;
}
String song = joinStringFrom(sub, 1);
for (String s : songs){
if (s.equals(song)){
player.getMap().broadcastMessage(MaplePacketCreator.musicChange(s));
player.yellowMessage("Now playing song " + song + ".");
return true;
}
}
player.yellowMessage("Song not found, please enter a song below.");
for (String s : songs){
player.yellowMessage(s);
}
} else if (sub[0].equals("monitor")) {
if (sub.length < 1){
player.yellowMessage("Syntax: !monitor <ign>");
return false;
}
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null){
player.yellowMessage("Player not found!");
return false;
}
boolean monitored = MapleLogger.monitored.contains(victim.getName());
if (monitored){
MapleLogger.monitored.remove(victim.getName());
} else {
MapleLogger.monitored.add(victim.getName());
}
player.yellowMessage(victim.getName() + " is " + (!monitored ? "now being monitored." : "no longer being monitored."));
String message = player.getName() + (!monitored ? " has started monitoring " : " has stopped monitoring ") + victim.getName() + ".";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
} else if (sub[0].equals("monitors")) {
for (String ign : MapleLogger.monitored){
player.yellowMessage(ign + " is being monitored.");
}
} else if (sub[0].equals("ignore")) {
if (sub.length < 1){
player.yellowMessage("Syntax: !ignore <ign>");
return false;
}
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null){
player.yellowMessage("Player not found!");
return false;
}
boolean monitored = MapleLogger.ignored.contains(victim.getName());
if (monitored){
MapleLogger.ignored.remove(victim.getName());
} else {
MapleLogger.ignored.add(victim.getName());
}
player.yellowMessage(victim.getName() + " is " + (!monitored ? "now being ignored." : "no longer being ignored."));
String message = player.getName() + (!monitored ? " has started ignoring " : " has stopped ignoring ") + victim.getName() + ".";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
} else if (sub[0].equals("ignored")) {
for (String ign : MapleLogger.ignored){
player.yellowMessage(ign + " is being ignored.");
}
} else if (sub[0].equals("pos")) {
float xpos = player.getPosition().x;
float ypos = player.getPosition().y;
float fh = player.getMap().getFootholds().findBelow(player.getPosition()).getId();
player.dropMessage("Position: (" + xpos + ", " + ypos + ")");
player.dropMessage("Foothold ID: " + fh);
} else if (sub[0].equals("dc")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !dc <playername>");
return false;
}
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {
victim = player.getMap().getCharacterByName(sub[1]);
if (victim != null) {
try {//sometimes bugged because the map = null
victim.getClient().disconnect(true, false);
player.getMap().removePlayer(victim);
} catch (Exception e) {
e.printStackTrace();
}
} else {
return true;
}
}
}
if (player.gmLevel() < victim.gmLevel()) {
victim = player;
}
victim.getClient().disconnect(false, false);
} else if (sub[0].equals("exprate")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !exprate <newrate>");
return false;
}
c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
} else if (sub[0].equals("chat")) {
player.toggleWhiteChat();
player.message("Your chat is now " + (player.getWhiteChat() ? " white" : "normal") + ".");
} else if (sub[0].equals("warpto")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !warpto <mapid>");
return false;
}
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {//If victim isn't on current channel or isnt a character try and find him by loop all channels on current world.
for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
if (victim != null) {
break;//We found the person, no need to continue the loop.
}
}
}
if (victim != null) {//If target isn't null attempt to warp.
//Remove warper from current event instance.
if (player.getEventInstance() != null) {
player.getEventInstance().unregisterPlayer(player);
}
//Attempt to join the victims warp instance.
if (victim.getEventInstance() != null) {
if (victim.getClient().getChannel() == player.getClient().getChannel()) {//just in case.. you never know...
//victim.getEventInstance().registerPlayer(player);
player.changeMap(victim.getEventInstance().getMapInstance(victim.getMapId()), victim.getMap().findClosestPortal(victim.getPosition()));
} else {
player.dropMessage("Please change to channel " + victim.getClient().getChannel());
}
} else {//If victim isn't in an event instance, just warp them.
player.changeMap(victim.getMapId(), victim.getMap().findClosestPortal(victim.getPosition()));
}
if (player.getClient().getChannel() != victim.getClient().getChannel()) {//And then change channel if needed.
player.dropMessage("Changing channel, please wait a moment.");
player.getClient().changeChannel(victim.getClient().getChannel());
}
} else {
player.dropMessage("Unknown player.");
}
} else if (sub[0].equals("warphere")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !warphere <playername>");
return false;
}
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {//If victim isn't on current channel, loop all channels on current world.
for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
if (victim != null) {
break;//We found the person, no need to continue the loop.
}
}
}
if (victim != null) {
if (victim.getEventInstance() != null) {
victim.getEventInstance().unregisterPlayer(victim);
}
//Attempt to join the warpers instance.
if (player.getEventInstance() != null) {
if (player.getClient().getChannel() == victim.getClient().getChannel()) {//just in case.. you never know...
player.getEventInstance().registerPlayer(victim);
victim.changeMap(player.getEventInstance().getMapInstance(player.getMapId()), player.getMap().findClosestPortal(player.getPosition()));
} else {
player.dropMessage("Target isn't on your channel, not able to warp into event instance.");
}
} else {//If victim isn't in an event instance, just warp them.
victim.changeMap(player.getMapId(), player.getMap().findClosestPortal(player.getPosition()));
}
if (player.getClient().getChannel() != victim.getClient().getChannel()) {//And then change channel if needed.
victim.dropMessage("Changing channel, please wait a moment.");
victim.getClient().changeChannel(player.getClient().getChannel());
}
} else {
player.dropMessage("Unknown player.");
}
} else if (sub[0].equals("fame")) {
if (sub.length < 3){
player.yellowMessage("Syntax: !fame <playername> <gainfame>");
return false;
}
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
victim.setFame(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.FAME, victim.getFame());
} else if (sub[0].equals("giftnx")) {
if (sub.length < 3){
player.yellowMessage("Syntax: !giftnx <playername> <gainnx>");
return false;
}
cserv.getPlayerStorage().getCharacterByName(sub[1]).getCashShop().gainCash(1, Integer.parseInt(sub[2]));
player.message("Done");
} else if (sub[0].equals("gmshop")) {
MapleShopFactory.getInstance().getShop(1337).sendShop(c);
} else if (sub[0].equals("heal")) {
player.setHpMp(30000);
} else if (sub[0].equals("vp")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !vp <gainvotepoint>");
return false;
}
c.addVotePoints(Integer.parseInt(sub[1]));
} else if (sub[0].equals("id")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !id <id>");
return false;
}
try {
try (BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + sub[1] + "&check=true").openConnection().getInputStream()))) {
String s;
while ((s = dis.readLine()) != null) {
player.dropMessage(s);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (sub[0].equals("item") || sub[0].equals("drop")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !item <itemid> <quantity>");
return false;
}
int itemId = Integer.parseInt(sub[1]);
short quantity = 1;
if(sub.length >= 3) quantity = Short.parseShort(sub[2]);
if (sub[0].equals("item")) {
int petid = -1;
if (ItemConstants.isPet(itemId)) {
petid = MaplePet.createPet(itemId);
}
MapleInventoryManipulator.addById(c, itemId, quantity, player.getName(), petid, -1);
} else {
Item toDrop;
if (MapleItemInformationProvider.getInstance().getInventoryType(itemId) == MapleInventoryType.EQUIP) {
toDrop = MapleItemInformationProvider.getInstance().getEquipById(itemId);
} else {
toDrop = new Item(itemId, (short) 0, quantity);
}
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
}
} else if (sub[0].equals("expeds")) {
for (Channel ch : Server.getInstance().getChannelsFromWorld(0)) {
if (ch.getExpeditions().size() == 0) {
player.yellowMessage("No Expeditions in Channel " + ch.getId());
continue;
}
player.yellowMessage("Expeditions in Channel " + ch.getId());
int id = 0;
for (MapleExpedition exped : ch.getExpeditions()) {
id++;
player.yellowMessage("> Expedition " + id);
player.yellowMessage(">> Type: " + exped.getType().toString());
player.yellowMessage(">> Status: " + (exped.isRegistering() ? "REGISTERING" : "UNDERWAY"));
player.yellowMessage(">> Size: " + exped.getMembers().size());
player.yellowMessage(">> Leader: " + exped.getLeader().getName());
int memId = 2;
for (MapleCharacter member : exped.getMembers()) {
if (exped.isLeader(member)) {
continue;
}
player.yellowMessage(">>> Member " + memId + ": " + member.getName());
memId++;
}
}
}
} else if (sub[0].equals("kill")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !kill <playername>");
return false;
}
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
victim.setHpMp(0);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !kill on " + victim.getName()));
} else if (sub[0].equals("seed")) {
if (player.getMapId() != 910010000) {
player.yellowMessage("This command can only be used in HPQ.");
return false;
}
Point pos[] = {new Point(7, -207), new Point(179, -447), new Point(-3, -687), new Point(-357, -687), new Point(-538, -447), new Point(-359, -207)};
int seed[] = {4001097, 4001096, 4001095, 4001100, 4001099, 4001098};
for (int i = 0; i < pos.length; i++) {
Item item = new Item(seed[i], (byte) 0, (short) 1);
player.getMap().spawnItemDrop(player, player, item, pos[i], false, true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else if (sub[0].equals("killall")) {
List<MapleMapObject> monsters = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
MapleMap map = player.getMap();
for (MapleMapObject monstermo : monsters) {
MapleMonster monster = (MapleMonster) monstermo;
if (!monster.getStats().isFriendly()) {
map.killMonster(monster, player, true);
monster.giveExpToCharacter(player, monster.getExp() * c.getPlayer().getExpRate(), true, 1);
}
}
player.dropMessage("Killed " + monsters.size() + " monsters.");
} else if (sub[0].equals("monsterdebug")) {
List<MapleMapObject> monsters = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
for (MapleMapObject monstermo : monsters) {
MapleMonster monster = (MapleMonster) monstermo;
player.message("Monster ID: " + monster.getId());
}
} else if (sub[0].equals("unbug")) {
c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.enableActions());
} else if (sub[0].equals("level")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !level <newlevel>");
return false;
}
player.setLevel(Integer.parseInt(sub[1]) - 1);
player.gainExp(-player.getExp(), false, false);
player.levelUp(false);
} else if (sub[0].equals("levelpro")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !levelpro <newlevel>");
return false;
}
while (player.getLevel() < Math.min(255, Integer.parseInt(sub[1]))) {
player.levelUp(false);
}
} else if (sub[0].equals("maxstat")) {
final String[] s = {"setall", String.valueOf(Short.MAX_VALUE)};
executeGMCommand(c, s, heading);
player.setLevel(255);
player.setFame(13337);
player.setMaxHp(30000);
player.setMaxMp(30000);
player.updateSingleStat(MapleStat.LEVEL, 255);
player.updateSingleStat(MapleStat.FAME, 13337);
player.updateSingleStat(MapleStat.MAXHP, 30000);
player.updateSingleStat(MapleStat.MAXMP, 30000);
} else if (sub[0].equals("maxskills")) {
for (MapleData skill_ : MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/" + "String.wz")).getData("Skill.img").getChildren()) {
try {
Skill skill = SkillFactory.getSkill(Integer.parseInt(skill_.getName()));
if (GameConstants.isInJobTree(skill.getId(), player.getJob().getId())) {
player.changeSkillLevel(skill, (byte) skill.getMaxLevel(), skill.getMaxLevel(), -1);
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
break;
} catch (NullPointerException npe) {
npe.printStackTrace();
continue;
}
}
} else if (sub[0].equals("mesos")) {
if (sub.length >= 2) {
player.gainMeso(Integer.parseInt(sub[1]), true);
}
} else if (sub[0].equals("notice")) {
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[Notice] " + joinStringFrom(sub, 1)));
} else if (sub[0].equals("rip")) {
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + joinStringFrom(sub, 1)));
} else if (sub[0].equals("openportal")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !openportal <portalid>");
return false;
}
player.getMap().getPortal(sub[1]).setPortalState(true);
} else if (sub[0].equals("pe")) {
String packet = "";
try {
InputStreamReader is = new FileReader("pe.txt");
Properties packetProps = new Properties();
packetProps.load(is);
is.close();
packet = packetProps.getProperty("pe");
} catch (IOException ex) {
ex.printStackTrace();
player.yellowMessage("Failed to load pe.txt");
return false;
}
MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter();
mplew.write(HexTool.getByteArrayFromHexString(packet));
SeekableLittleEndianAccessor slea = new GenericSeekableLittleEndianAccessor(new ByteArrayByteStream(mplew.getPacket()));
short packetId = slea.readShort();
final MaplePacketHandler packetHandler = PacketProcessor.getProcessor(0, c.getChannel()).getHandler(packetId);
if (packetHandler != null && packetHandler.validateState(c)) {
try {
player.yellowMessage("Recieving: " + packet);
packetHandler.handlePacket(slea, c);
} catch (final Throwable t) {
FilePrinter.printError(FilePrinter.PACKET_HANDLER + packetHandler.getClass().getName() + ".txt", t, "Error for " + (c.getPlayer() == null ? "" : "player ; " + c.getPlayer() + " on map ; " + c.getPlayer().getMapId() + " - ") + "account ; " + c.getAccountName() + "\r\n" + slea.toString());
return false;
}
}
} else if (sub[0].equals("closeportal")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !closeportal <portalid>");
return false;
}
player.getMap().getPortal(sub[1]).setPortalState(false);
} else if (sub[0].equals("startevent")) {
for (MapleCharacter chr : player.getMap().getCharacters()) {
player.getMap().startEvent(chr);
}
c.getChannelServer().setEvent(null);
} else if (sub[0].equals("scheduleevent")) {
int players = 50;
if(sub.length > 1)
players = Integer.parseInt(sub[1]);
c.getChannelServer().setEvent(new MapleEvent(player.getMapId(), players));
player.dropMessage(5, "The event has been set on " + player.getMap().getMapName() + " and will allow " + players + " players to join.");
} else if(sub[0].equals("endevent")) {
c.getChannelServer().setEvent(null);
player.dropMessage(5, "You have ended the event. No more players may join.");
} else if (sub[0].equals("online2")) {
int total = 0;
for (Channel ch : srv.getChannelsFromWorld(player.getWorld())) {
int size = ch.getPlayerStorage().getAllCharacters().size();
total += size;
String s = "(Channel " + ch.getId() + " Online: " + size + ") : ";
if (ch.getPlayerStorage().getAllCharacters().size() < 50) {
for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
}
player.dropMessage(s.substring(0, s.length() - 2));
}
}
player.dropMessage("There are a total of " + total + " players online.");
} else if (sub[0].equals("pap")) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8500001), player.getPosition());
} else if (sub[0].equals("pianus")) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8510000), player.getPosition());
} else if (sub[0].equalsIgnoreCase("search")) {
if (sub.length < 3){
player.yellowMessage("Syntax: !search <type> <name>");
return false;
}
StringBuilder sb = new StringBuilder();
String search = joinStringFrom(sub, 2);
long start = System.currentTimeMillis();//for the lulz
MapleData data = null;
MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
if (!sub[1].equalsIgnoreCase("ITEM")) {
if (sub[1].equalsIgnoreCase("NPC")) {
data = dataProvider.getData("Npc.img");
} else if (sub[1].equalsIgnoreCase("MOB") || sub[1].equalsIgnoreCase("MONSTER")) {
data = dataProvider.getData("Mob.img");
} else if (sub[1].equalsIgnoreCase("SKILL")) {
data = dataProvider.getData("Skill.img");
} else if (sub[1].equalsIgnoreCase("MAP")) {
sb.append("#bUse the '/m' command to find a map. If it finds a map with the same name, it will warp you to it.");
} else {
sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
}
if (data != null) {
String name;
for (MapleData searchData : data.getChildren()) {
name = MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
if (name.toLowerCase().contains(search.toLowerCase())) {
sb.append("#b").append(Integer.parseInt(searchData.getName())).append("#k - #r").append(name).append("\r\n");
}
}
}
} else {
for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
if (sb.length() < 32654) {//ohlol
if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
//#v").append(id).append("# #k-
sb.append("#b").append(itemPair.getLeft()).append("#k - #r").append(itemPair.getRight()).append("\r\n");
}
} else {
sb.append("#bCouldn't load all items, there are too many results.\r\n");
break;
}
}
}
if (sb.length() == 0) {
sb.append("#bNo ").append(sub[1].toLowerCase()).append("s found.\r\n");
}
sb.append("\r\n#kLoaded within ").append((double) (System.currentTimeMillis() - start) / 1000).append(" seconds.");//because I can, and it's free
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, sb.toString(), "00 00", (byte) 0));
} else if (sub[0].equals("servermessage")) {
c.getWorldServer().setServerMessage(joinStringFrom(sub, 1));
} else if (sub[0].equals("warpsnowball")) {
List<MapleCharacter> chars = new ArrayList<>(player.getMap().getCharacters());
for (MapleCharacter chr : chars) {
chr.changeMap(109060000, chr.getTeam());
}
} else if (sub[0].equals("setall")) {
final int x = Short.parseShort(sub[1]);
player.setStr(x);
player.setDex(x);
player.setInt(x);
player.setLuk(x);
player.updateSingleStat(MapleStat.STR, x);
player.updateSingleStat(MapleStat.DEX, x);
player.updateSingleStat(MapleStat.INT, x);
player.updateSingleStat(MapleStat.LUK, x);
} else if (sub[0].equals("unban")) {
if (sub.length < 2){
player.yellowMessage("Syntax: !unban <playername>");
return false;
}
try {
Connection con = DatabaseConnection.getConnection();
int aid = MapleCharacter.getAccountIdByName(sub[1]);
PreparedStatement p = con.prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + aid);
p.executeUpdate();
p = con.prepareStatement("DELETE FROM ipbans WHERE aid = " + aid);
p.executeUpdate();
p = con.prepareStatement("DELETE FROM macbans WHERE aid = " + aid);
p.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
player.message("Failed to unban " + sub[1]);
return true;
}
player.message("Unbanned " + sub[1]);
} else if (sub[0].equals("ban")) {
if (sub.length < 3) {
player.yellowMessage("Syntax: !ban <IGN> <Reason> (Please be descriptive)");
return false;
}
String ign = sub[1];
String reason = joinStringFrom(sub, 2);
MapleCharacter target = c.getChannelServer().getPlayerStorage().getCharacterByName(ign);
if (target != null) {
String readableTargetName = MapleCharacter.makeMapleReadable(target.getName());
String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0];
//Ban ip
PreparedStatement ps = null;
try {
Connection con = DatabaseConnection.getConnection();
if (ip.matches("/[0-9]{1,3}\\..*")) {
ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?, ?)");
ps.setString(1, ip);
ps.setString(2, String.valueOf(target.getClient().getAccID()));
ps.executeUpdate();
ps.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
c.getPlayer().message("Error occured while banning IP address");
c.getPlayer().message(target.getName() + "'s IP was not banned: " + ip);
}
target.getClient().banMacs();
reason = c.getPlayer().getName() + " banned " + readableTargetName + " for " + reason + " (IP: " + ip + ") " + "(MAC: " + c.getMacs() + ")";
target.ban(reason);
target.yellowMessage("You have been banned by #b" + c.getPlayer().getName() + " #k.");
target.yellowMessage("Reason: " + reason);
c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
final MapleCharacter rip = target;
TimerManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
rip.getClient().disconnect(false, false);
}
}, 5000); //5 Seconds
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
} else if (MapleCharacter.ban(ign, reason, false)) {
c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
} else {
c.announce(MaplePacketCreator.getGMEffect(6, (byte) 1));
}
} else if (sub[0].equalsIgnoreCase("night")) {
player.getMap().broadcastNightEffect();
player.yellowMessage("Done.");
} else {
return false;
}
return true;
}
public static void executeAdminCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
switch (sub[0]) {
case "sp": //Changed to support giving sp /a
if (sub.length < 2){
player.yellowMessage("Syntax: !sp <newsp>");
return;
}
if (sub.length == 2) {
player.setRemainingSp(Integer.parseInt(sub[1]));
player.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
} else {
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.setRemainingSp(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
}
break;
case "horntail":
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8810026), player.getPosition());
break;
case "packet":
player.getMap().broadcastMessage(MaplePacketCreator.customPacket(joinStringFrom(sub, 1)));
break;
case "timerdebug":
TimerManager tMan = TimerManager.getInstance();
player.dropMessage(6, "Total Task: " + tMan.getTaskCount() + " Current Task: " + tMan.getQueuedTasks() + " Active Task: " + tMan.getActiveCount() + " Completed Task: " + tMan.getCompletedTaskCount());
break;
case "warpworld":
if (sub.length < 2){
player.yellowMessage("Syntax: !warpworld <worldid>");
return;
}
Server server = Server.getInstance();
byte worldb = Byte.parseByte(sub[1]);
if (worldb <= (server.getWorlds().size() - 1)) {
try {
String[] socket = server.getIP(worldb, c.getChannel()).split(":");
c.getWorldServer().removePlayer(player);
player.getMap().removePlayer(player);//LOL FORGOT THIS ><
c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
player.setWorld(worldb);
player.saveToDB();//To set the new world :O (true because else 2 player instances are created, one in both worlds)
c.announce(MaplePacketCreator.getChannelChange(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1])));
} catch (UnknownHostException | NumberFormatException ex) {
ex.printStackTrace();
player.message("Error when trying to change worlds, are you sure the world you are trying to warp to has the same amount of channels?");
}
} else {
player.message("Invalid world; highest number available: " + (server.getWorlds().size() - 1));
}
break;
case "saveall"://fyi this is a stupid command
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
chr.saveToDB();
}
}
String message = player.getName() + " used !saveall.";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
player.message("All players saved successfully.");
break;
case "dcall":
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
if (!chr.isGM()) {
chr.getClient().disconnect(false, false);
}
}
}
player.message("All players successfully disconnected.");
break;
case "mapplayers"://fyi this one is even stupider
//Adding HP to it, making it less useless.
String names = "";
int map = player.getMapId();
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
int curMap = chr.getMapId();
String hp = Integer.toString(chr.getHp());
String maxhp = Integer.toString(chr.getMaxHp());
String name = chr.getName() + ": " + hp + "/" + maxhp;
if (map == curMap) {
names = names.equals("") ? name : (names + ", " + name);
}
}
}
player.message("These b lurkin: " + names);
break;
case "getacc":
if (sub.length < 2){
player.yellowMessage("Syntax: !getacc <playername>");
return;
}
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.message(victim.getName() + "'s account name is " + victim.getClient().getAccountName() + ".");
break;
case "npc":
if (sub.length < 2){
player.yellowMessage("Syntax: !npc <npcid>");
return;
}
MapleNPC npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
if (npc != null) {
npc.setPosition(player.getPosition());
npc.setCy(player.getPosition().y);
npc.setRx0(player.getPosition().x + 50);
npc.setRx1(player.getPosition().x - 50);
npc.setFh(player.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
player.getMap().addMapObject(npc);
player.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
}
break;
case "job": { //Honestly, we should merge this with @job and job yourself if array is 1 long only. I'll do it but gotta run at this point lel
//Alright, doing that. /a
if (sub.length == 2) {
player.changeJob(MapleJob.getById(Integer.parseInt(sub[1])));
player.equipChanged();
} else if (sub.length == 3) {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.changeJob(MapleJob.getById(Integer.parseInt(sub[2])));
player.equipChanged();
} else {
player.message("!job <job id> <opt: IGN of another person>");
}
break;
}
case "playernpc":
if (sub.length < 3){
player.yellowMessage("Syntax: !playernpc <playername> <npcid>");
return;
}
player.playerNPC(c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]), Integer.parseInt(sub[2]));
break;
case "shutdown":
case "shutdownnow":
int time = 60000;
if (sub[0].equals("shutdownnow")) {
time = 1;
} else if (sub.length > 1) {
time *= Integer.parseInt(sub[1]);
}
TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
break;
case "face":
if (sub.length < 2){
player.yellowMessage("Syntax: !face <faceid>");
return;
}
if (sub.length == 2) {
player.setFace(Integer.parseInt(sub[1]));
player.equipChanged();
} else {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.setFace(Integer.parseInt(sub[2]));
player.equipChanged();
}
break;
case "hair":
if (sub.length < 2){
player.yellowMessage("Syntax: !hair <hairid>");
return;
}
if (sub.length == 2) {
player.setHair(Integer.parseInt(sub[1]));
player.equipChanged();
} else {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.setHair(Integer.parseInt(sub[2]));
player.equipChanged();
}
break;
case "itemvac":
List<MapleMapObject> items = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.ITEM));
for (MapleMapObject item : items) {
MapleMapItem mapitem = (MapleMapItem) item;
if (!MapleInventoryManipulator.addFromDrop(c, mapitem.getItem(), true)) {
continue;
}
mapitem.setPickedUp(true);
player.getMap().broadcastMessage(MaplePacketCreator.removeItemFromMap(mapitem.getObjectId(), 2, player.getId()), mapitem.getPosition());
player.getMap().removeMapObject(item);
}
break;
case "zakum":
player.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), player.getPosition());
for (int x = 8800003; x < 8800011; x++) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(x), player.getPosition());
}
break;
case "clearquestcache":
MapleQuest.clearCache();
player.dropMessage(5, "Quest Cache Cleared.");
break;
case "clearquest":
if(sub.length < 1) {
player.dropMessage(5, "Plese include a quest ID.");
return;
}
MapleQuest.clearCache(Integer.parseInt(sub[1]));
player.dropMessage(5, "Quest Cache for quest " + sub[1] + " cleared.");
break;
default:
player.yellowMessage("Command " + heading + sub[0] + " does not exist.");
break;
}
}
private static String joinStringFrom(String arr[], int start) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
builder.append(arr[i]);
if (i != arr.length - 1) {
builder.append(" ");
}
}
return builder.toString();
}
}
| src/client/command/Commands.java | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.te
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client.command;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import net.MaplePacketHandler;
import net.PacketProcessor;
import net.server.Server;
import net.server.channel.Channel;
import net.server.world.World;
import provider.MapleData;
import provider.MapleDataProvider;
import provider.MapleDataProviderFactory;
import provider.MapleDataTool;
import scripting.npc.NPCScriptManager;
import scripting.portal.PortalScriptManager;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MaplePortal;
import server.MapleShopFactory;
import server.TimerManager;
import server.events.gm.MapleEvent;
import server.expeditions.MapleExpedition;
import server.gachapon.MapleGachapon.Gachapon;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleMonsterInformationProvider;
import server.life.MapleNPC;
import server.life.MonsterDropEntry;
import server.maps.MapleMap;
import server.maps.MapleMapItem;
import server.maps.MapleMapObject;
import server.maps.MapleMapObjectType;
import server.quest.MapleQuest;
import tools.DatabaseConnection;
import tools.FilePrinter;
import tools.HexTool;
import tools.MapleLogger;
import tools.MaplePacketCreator;
import tools.Pair;
import tools.Randomizer;
import tools.data.input.ByteArrayByteStream;
import tools.data.input.GenericSeekableLittleEndianAccessor;
import tools.data.input.SeekableLittleEndianAccessor;
import tools.data.output.MaplePacketLittleEndianWriter;
import client.MapleBuffStat;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleJob;
import client.MapleStat;
import client.Skill;
import client.SkillFactory;
import client.inventory.Item;
import client.inventory.MapleInventoryType;
import client.inventory.MaplePet;
import constants.GameConstants;
import constants.ItemConstants;
import constants.ServerConstants;
import java.util.ArrayList;
import server.maps.FieldLimit;
public class Commands {
private static HashMap<String, Integer> gotomaps = new HashMap<String, Integer>();
private static String[] tips = {
"Please only use @gm in emergencies or to report somebody.",
"To report a bug or make a suggestion, use the forum.",
"Please do not use @gm to ask if a GM is online.",
"Do not ask if you can receive help, just state your issue.",
"Do not say 'I have a bug to report', just state it.",
};
private static String[] songs = {
"Jukebox/Congratulation",
"Bgm00/SleepyWood",
"Bgm00/FloralLife",
"Bgm00/GoPicnic",
"Bgm00/Nightmare",
"Bgm00/RestNPeace",
"Bgm01/AncientMove",
"Bgm01/MoonlightShadow",
"Bgm01/WhereTheBarlogFrom",
"Bgm01/CavaBien",
"Bgm01/HighlandStar",
"Bgm01/BadGuys",
"Bgm02/MissingYou",
"Bgm02/WhenTheMorningComes",
"Bgm02/EvilEyes",
"Bgm02/JungleBook",
"Bgm02/AboveTheTreetops",
"Bgm03/Subway",
"Bgm03/Elfwood",
"Bgm03/BlueSky",
"Bgm03/Beachway",
"Bgm03/SnowyVillage",
"Bgm04/PlayWithMe",
"Bgm04/WhiteChristmas",
"Bgm04/UponTheSky",
"Bgm04/ArabPirate",
"Bgm04/Shinin'Harbor",
"Bgm04/WarmRegard",
"Bgm05/WolfWood",
"Bgm05/DownToTheCave",
"Bgm05/AbandonedMine",
"Bgm05/MineQuest",
"Bgm05/HellGate",
"Bgm06/FinalFight",
"Bgm06/WelcomeToTheHell",
"Bgm06/ComeWithMe",
"Bgm06/FlyingInABlueDream",
"Bgm06/FantasticThinking",
"Bgm07/WaltzForWork",
"Bgm07/WhereverYouAre",
"Bgm07/FunnyTimeMaker",
"Bgm07/HighEnough",
"Bgm07/Fantasia",
"Bgm08/LetsMarch",
"Bgm08/ForTheGlory",
"Bgm08/FindingForest",
"Bgm08/LetsHuntAliens",
"Bgm08/PlotOfPixie",
"Bgm09/DarkShadow",
"Bgm09/TheyMenacingYou",
"Bgm09/FairyTale",
"Bgm09/FairyTalediffvers",
"Bgm09/TimeAttack",
"Bgm10/Timeless",
"Bgm10/TimelessB",
"Bgm10/BizarreTales",
"Bgm10/TheWayGrotesque",
"Bgm10/Eregos",
"Bgm11/BlueWorld",
"Bgm11/Aquarium",
"Bgm11/ShiningSea",
"Bgm11/DownTown",
"Bgm11/DarkMountain",
"Bgm12/AquaCave",
"Bgm12/DeepSee",
"Bgm12/WaterWay",
"Bgm12/AcientRemain",
"Bgm12/RuinCastle",
"Bgm12/Dispute",
"Bgm13/CokeTown",
"Bgm13/Leafre",
"Bgm13/Minar'sDream",
"Bgm13/AcientForest",
"Bgm13/TowerOfGoddess",
"Bgm14/DragonLoad",
"Bgm14/HonTale",
"Bgm14/CaveOfHontale",
"Bgm14/DragonNest",
"Bgm14/Ariant",
"Bgm14/HotDesert",
"Bgm15/MureungHill",
"Bgm15/MureungForest",
"Bgm15/WhiteHerb",
"Bgm15/Pirate",
"Bgm15/SunsetDesert",
"Bgm16/Duskofgod",
"Bgm16/FightingPinkBeen",
"Bgm16/Forgetfulness",
"Bgm16/Remembrance",
"Bgm16/Repentance",
"Bgm16/TimeTemple",
"Bgm17/MureungSchool1",
"Bgm17/MureungSchool2",
"Bgm17/MureungSchool3",
"Bgm17/MureungSchool4",
"Bgm18/BlackWing",
"Bgm18/DrillHall",
"Bgm18/QueensGarden",
"Bgm18/RaindropFlower",
"Bgm18/WolfAndSheep",
"Bgm19/BambooGym",
"Bgm19/CrystalCave",
"Bgm19/MushCatle",
"Bgm19/RienVillage",
"Bgm19/SnowDrop",
"Bgm20/GhostShip",
"Bgm20/NetsPiramid",
"Bgm20/UnderSubway",
"Bgm21/2021year",
"Bgm21/2099year",
"Bgm21/2215year",
"Bgm21/2230year",
"Bgm21/2503year",
"Bgm21/KerningSquare",
"Bgm21/KerningSquareField",
"Bgm21/KerningSquareSubway",
"Bgm21/TeraForest",
"BgmEvent/FunnyRabbit",
"BgmEvent/FunnyRabbitFaster",
"BgmEvent/wedding",
"BgmEvent/weddingDance",
"BgmEvent/wichTower",
"BgmGL/amoria",
"BgmGL/Amorianchallenge",
"BgmGL/chapel",
"BgmGL/cathedral",
"BgmGL/Courtyard",
"BgmGL/CrimsonwoodKeep",
"BgmGL/CrimsonwoodKeepInterior",
"BgmGL/GrandmastersGauntlet",
"BgmGL/HauntedHouse",
"BgmGL/NLChunt",
"BgmGL/NLCtown",
"BgmGL/NLCupbeat",
"BgmGL/PartyQuestGL",
"BgmGL/PhantomForest",
"BgmJp/Feeling",
"BgmJp/BizarreForest",
"BgmJp/Hana",
"BgmJp/Yume",
"BgmJp/Bathroom",
"BgmJp/BattleField",
"BgmJp/FirstStepMaster",
"BgmMY/Highland",
"BgmMY/KualaLumpur",
"BgmSG/BoatQuay_field",
"BgmSG/BoatQuay_town",
"BgmSG/CBD_field",
"BgmSG/CBD_town",
"BgmSG/Ghostship",
"BgmUI/ShopBgm",
"BgmUI/Title"
};
static {
gotomaps.put("gmmap", 180000000);
gotomaps.put("southperry", 60000);
gotomaps.put("amherst", 1010000);
gotomaps.put("henesys", 100000000);
gotomaps.put("ellinia", 101000000);
gotomaps.put("perion", 102000000);
gotomaps.put("kerning", 103000000);
gotomaps.put("lith", 104000000);
gotomaps.put("sleepywood", 105040300);
gotomaps.put("florina", 110000000);
gotomaps.put("orbis", 200000000);
gotomaps.put("happy", 209000000);
gotomaps.put("elnath", 211000000);
gotomaps.put("ludi", 220000000);
gotomaps.put("aqua", 230000000);
gotomaps.put("leafre", 240000000);
gotomaps.put("mulung", 250000000);
gotomaps.put("herb", 251000000);
gotomaps.put("omega", 221000000);
gotomaps.put("korean", 222000000);
gotomaps.put("nlc", 600000000);
gotomaps.put("excavation", 990000000);
gotomaps.put("pianus", 230040420);
gotomaps.put("horntail", 240060200);
gotomaps.put("mushmom", 100000005);
gotomaps.put("griffey", 240020101);
gotomaps.put("manon", 240020401);
gotomaps.put("horseman", 682000001);
gotomaps.put("balrog", 105090900);
gotomaps.put("zakum", 211042300);
gotomaps.put("papu", 220080001);
gotomaps.put("showa", 801000000);
gotomaps.put("guild", 200000301);
gotomaps.put("shrine", 800000000);
gotomaps.put("skelegon", 240040511);
gotomaps.put("hpq", 100000200);
gotomaps.put("ht", 240050400);
gotomaps.put("fm", 910000000);
}
public static boolean executePlayerCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
if (heading == '!' && player.gmLevel() == 0) {
player.yellowMessage("You may not use !" + sub[0] + ", please try /" + sub[0]);
return false;
}
switch (sub[0]) {
case "help":
case "commands":
player.yellowMessage("After you vote, talk to Rooney to get a leaf and redeem it for prizes!");
player.message("@dispose: Fixes your character if it is stuck.");
player.message("@online: Displays a list of all online players.");
player.message("@time: Displays the current server time.");
player.message("@rates: Displays your current DROP, MESO and EXP rates.");
player.message("@points: Tells you how many unused vote points you have and when/if you can vote.");
player.message("@gm <message>: Sends a message to all online GMs in the case of an emergency.");
player.message("@bug <bug>: Sends a bug report to all developers.");
player.message("@joinevent: If an event is in progress, use this to warp to the event map.");
player.message("@leaveevent: If an event has ended, use this to warp to your original map.");
player.message("@staff: Lists the staff of Solaxia.");
player.message("@uptime: Shows how long Solaxia has been online.");
player.message("@whatdropsfrom <monster name>: Displays a list of drops and chances for a specified monster.");
player.message("@whodrops <item name>: Displays monsters that drop an item given an item name.");
player.message("@uptime: Shows how long Solaxia has been online.");
player.message("@bosshp: Displays the remaining HP of the bosses on your map.");
if(ServerConstants.USE_DEBUG) {
player.message("@debugpos: Displays the coordinates on the map the player is currently located.");
player.message("@debugmap: Displays info about the current map the player is located.");
player.message("@debugevent: Displays the name of the event in which the player is currently registered.");
player.message("@debugreactors: Displays current info for all reactors on the map the the player is currently located.");
}
break;
case "time":
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
player.yellowMessage("Solaxia Server Time: " + dateFormat.format(new Date()));
break;
case "staff":
player.yellowMessage("MapleSolaxia Staff");
player.yellowMessage("Aria - Administrator");
player.yellowMessage("Twdtwd - Administrator");
player.yellowMessage("Exorcist - Developer");
player.yellowMessage("SharpAceX - Developer");
player.yellowMessage("Zygon - Freelance Developer");
player.yellowMessage("SourMjolk - Game Master");
player.yellowMessage("Kanade - Game Master");
player.yellowMessage("Kitsune - Game Master");
player.yellowMessage("Branch Staff");
player.yellowMessage("Ronan - Freelance Developer");
break;
case "lastrestart":
case "uptime":
long milliseconds = System.currentTimeMillis() - Server.uptime;
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
int days = (int) ((milliseconds / (1000*60*60*24)));
player.yellowMessage("Solaxia has been online for " + days + " days " + hours + " hours " + minutes + " minutes and " + seconds + " seconds.");
break;
case "gacha":
if (player.gmLevel() == 0) { // Sigh, need it for now...
player.yellowMessage("Player Command " + heading + sub[0] + " does not exist, see @help for a list of commands.");
return false;
}
Gachapon gacha = null;
String search = joinStringFrom(sub, 1);
String gachaName = "";
String [] names = {"Henesys", "Ellinia", "Perion", "Kerning City", "Sleepywood", "Mushroom Shrine", "Showa Spa Male", "Showa Spa Female", "New Leaf City", "Nautilus Harbor"};
int [] ids = {9100100, 9100101, 9100102, 9100103, 9100104, 9100105, 9100106, 9100107, 9100109, 9100117};
for (int i = 0; i < names.length; i++){
if (search.equalsIgnoreCase(names[i])){
gachaName = names[i];
gacha = Gachapon.getByNpcId(ids[i]);
}
}
if (gacha == null){
player.yellowMessage("Please use @gacha <name> where name corresponds to one of the below:");
for (String name : names){
player.yellowMessage(name);
}
break;
}
String output = "The #b" + gachaName + "#k Gachapon contains the following items.\r\n\r\n";
for (int i = 0; i < 2; i++){
for (int id : gacha.getItems(i)){
output += "-" + MapleItemInformationProvider.getInstance().getName(id) + "\r\n";
}
}
output += "\r\nPlease keep in mind that there are items that are in all gachapons and are not listed here.";
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "whatdropsfrom":
if (sub.length < 2) {
player.dropMessage(5, "Please do @whatdropsfrom <monster name>");
break;
}
String monsterName = joinStringFrom(sub, 1);
output = "";
int limit = 3;
Iterator<Pair<Integer, String>> listIterator = MapleMonsterInformationProvider.getMobsIDsFromName(monsterName).iterator();
for (int i = 0; i < limit; i++) {
if(listIterator.hasNext()) {
Pair<Integer, String> data = listIterator.next();
int mobId = data.getLeft();
String mobName = data.getRight();
output += mobName + " drops the following items:\r\n\r\n";
for (MonsterDropEntry drop : MapleMonsterInformationProvider.getInstance().retrieveDrop(mobId)){
try {
String name = MapleItemInformationProvider.getInstance().getName(drop.itemId);
if (name.equals("null") || drop.chance == 0){
continue;
}
float chance = 1000000 / drop.chance / player.getDropRate();
output += "- " + name + " (1/" + (int) chance + ")\r\n";
} catch (Exception ex){
ex.printStackTrace();
continue;
}
}
output += "\r\n";
}
}
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "whodrops":
if (sub.length < 2) {
player.dropMessage(5, "Please do @whodrops <item name>");
break;
}
String searchString = joinStringFrom(sub, 1);
output = "";
listIterator = MapleItemInformationProvider.getInstance().getItemDataByName(searchString).iterator();
if(listIterator.hasNext()) {
int count = 1;
while(listIterator.hasNext() && count <= 3) {
Pair<Integer, String> data = listIterator.next();
output += "#b" + data.getRight() + "#k is dropped by:\r\n";
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM drop_data WHERE itemid = ? LIMIT 50");
ps.setInt(1, data.getLeft());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String resultName = MapleMonsterInformationProvider.getMobNameFromID(rs.getInt("dropperid"));
if (resultName != null) {
output += resultName + ", ";
}
}
rs.close();
ps.close();
} catch (Exception e) {
player.dropMessage("There was a problem retreiving the required data. Please try again.");
e.printStackTrace();
return true;
}
output += "\r\n\r\n";
count++;
}
} else {
player.dropMessage(5, "The item you searched for doesn't exist.");
break;
}
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, output, "00 00", (byte) 0));
break;
case "dispose":
NPCScriptManager.getInstance().dispose(c);
c.announce(MaplePacketCreator.enableActions());
c.removeClickedNPC();
player.message("You've been disposed.");
break;
case "rates":
c.resetVoteTime();
player.yellowMessage("DROP RATE");
player.message(">>Base DROP Rate: " + c.getWorldServer().getDropRate() + "x");
player.message(">>Your DROP Rate: " + player.getDropRate() / c.getWorldServer().getDropRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total DROP Rate: " + player.getDropRate() + "x");
player.yellowMessage("MESO RATE");
player.message(">>Base MESO Rate: " + c.getWorldServer().getMesoRate() + "x");
player.message(">>Your MESO Rate: " + player.getMesoRate() / c.getWorldServer().getMesoRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total MESO Rate: " + player.getMesoRate() + "x");
player.yellowMessage("EXP RATE");
player.message(">>Base EXP Rate: " + c.getWorldServer().getExpRate() + "x");
player.message(">>Your EXP Rate: " + player.getExpRate() / c.getWorldServer().getExpRate() + "x");
player.message(">>------------------------------------------------");
player.message(">>Total EXP Rate: " + player.getExpRate() + "x");
/*if(c.getWorldServer().getExpRate() > ServerConstants.EXP_RATE) {
player.message(">>Event EXP bonus: " + (c.getWorldServer().getExpRate() - ServerConstants.EXP_RATE) + "x");
}
player.message(">>Voted EXP bonus: " + (c.hasVotedAlready() ? "1x" : "0x (If you vote now, you will earn an additional 1x EXP!)"));
if (player.getLevel() < 10) {
player.message("Players under level 10 always have 1x exp.");
}*/
break;
case "online":
for (Channel ch : Server.getInstance().getChannelsFromWorld(player.getWorld())) {
player.yellowMessage("Players in Channel " + ch.getId() + ":");
for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
if (!chr.isGM()) {
player.message(" >> " + MapleCharacter.makeMapleReadable(chr.getName()) + " is at " + chr.getMap().getMapName() + ".");
}
}
}
break;
case "gm":
if (sub.length < 3) { // #goodbye 'hi'
player.dropMessage(5, "Your message was too short. Please provide as much detail as possible.");
break;
}
String message = joinStringFrom(sub, 1);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.sendYellowTip("[GM MESSAGE]:" + MapleCharacter.makeMapleReadable(player.getName()) + ": " + message));
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(1, message));
FilePrinter.printError("gm.txt", MapleCharacter.makeMapleReadable(player.getName()) + ": " + message + "\r\n");
player.dropMessage(5, "Your message '" + message + "' was sent to GMs.");
player.dropMessage(5, tips[Randomizer.nextInt(tips.length)]);
break;
case "bug":
if (sub.length < 2) {
player.dropMessage(5, "Message too short and not sent. Please do @bug <bug>");
break;
}
message = joinStringFrom(sub, 1);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.sendYellowTip("[BUG]:" + MapleCharacter.makeMapleReadable(player.getName()) + ": " + message));
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(1, message));
FilePrinter.printError("bug.txt", MapleCharacter.makeMapleReadable(player.getName()) + ": " + message + "\r\n");
player.dropMessage(5, "Your bug '" + message + "' was submitted successfully to our developers. Thank you!");
break;
/*
case "points":
player.dropMessage(5, "You have " + c.getVotePoints() + " vote point(s).");
if (c.hasVotedAlready()) {
Date currentDate = new Date();
int time = (int) ((int) 86400 - ((currentDate.getTime() / 1000) - c.getVoteTime())); //ugly as fuck
hours = time / 3600;
minutes = time % 3600 / 60;
seconds = time % 3600 % 60;
player.yellowMessage("You have already voted. You can vote again in " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
} else {
player.yellowMessage("You are free to vote! Make sure to vote to gain a vote point!");
}
break;
*/
case "joinevent":
case "event":
case "join":
if(!FieldLimit.CHANGECHANNEL.check(player.getMap().getFieldLimit())) {
MapleEvent event = c.getChannelServer().getEvent();
if(event != null) {
if(event.getMapId() != player.getMapId()) {
if(event.getLimit() > 0) {
player.saveLocation("EVENT");
if(event.getMapId() == 109080000 || event.getMapId() == 109060001)
player.setTeam(event.getLimit() % 2);
event.minusLimit();
player.changeMap(event.getMapId());
} else {
player.dropMessage("The limit of players for the event has already been reached.");
}
} else {
player.dropMessage(5, "You are already in the event.");
}
} else {
player.dropMessage(5, "There is currently no event in progress.");
}
} else {
player.dropMessage(5, "You are currently in a map where you can't join an event.");
}
break;
case "leaveevent":
case "leave":
int returnMap = player.getSavedLocation("EVENT");
if(returnMap != -1) {
if(player.getOla() != null) {
player.getOla().resetTimes();
player.setOla(null);
}
if(player.getFitness() != null) {
player.getFitness().resetTimes();
player.setFitness(null);
}
player.changeMap(returnMap);
if(c.getChannelServer().getEvent() != null) {
c.getChannelServer().getEvent().addLimit();
}
} else {
player.dropMessage(5, "You are not currently in an event.");
}
break;
case "bosshp":
for(MapleMonster monster : player.getMap().getMonsters()) {
if(monster != null && monster.isBoss() && monster.getHp() > 0) {
long percent = monster.getHp() * 100L / monster.getMaxHp();
String bar = "[";
for (int i = 0; i < 100; i++){
bar += i < percent ? "|" : ".";
}
bar += "]";
player.yellowMessage(monster.getName() + " has " + percent + "% HP left.");
player.yellowMessage("HP: " + bar);
}
}
break;
case "ranks":
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = DatabaseConnection.getConnection().prepareStatement("SELECT `characters`.`name`, `characters`.`level` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` = '0' AND `accounts`.`banned` = '0' ORDER BY level DESC, exp DESC LIMIT 50");
rs = ps.executeQuery();
player.announce(MaplePacketCreator.showPlayerRanks(9010000, rs));
ps.close();
rs.close();
} catch(SQLException ex) {
ex.printStackTrace();
} finally {
try {
if(ps != null && !ps.isClosed()) {
ps.close();
}
if(rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
break;
//debug only
case "debugpos":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current map position: (" + player.getPosition().getX() + ", " + player.getPosition().getY() + ").");
}
break;
case "debugmap":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current map id " + player.getMap().getId() + ", event: '" + ((player.getMap().getEventInstance() != null) ? player.getMap().getEventInstance().getName() : "null") + "'; Players: " + player.getMap().getAllPlayers().size() + ", Mobs: " + player.getMap().countMonsters() + ", Reactors: " + player.getMap().countReactors() + ".");
}
break;
case "debugevent":
if(ServerConstants.USE_DEBUG) {
if(player.getEventInstance() == null) player.dropMessage("Player currently not in an event.");
else player.dropMessage("Current event name: " + player.getEventInstance().getName() + ".");
}
break;
case "debugreactors":
if(ServerConstants.USE_DEBUG) {
player.dropMessage("Current reactor states on map " + player.getMapId() + ":");
for(Pair p: player.getMap().reportReactorStates()) {
player.dropMessage("Reactor id: " + p.getLeft() + " -> State: " + p.getRight() + ".");
}
}
break;
default:
if (player.gmLevel() == 0) {
player.yellowMessage("Player Command " + heading + sub[0] + " does not exist, see @help for a list of commands.");
}
return false;
}
return true;
}
public static boolean executeGMCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
Channel cserv = c.getChannelServer();
Server srv = Server.getInstance();
if (sub[0].equals("ap")) {
if (sub.length < 3) {
player.setRemainingAp(Integer.parseInt(sub[1]));
player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
} else {
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.setRemainingAp(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.AVAILABLEAP, victim.getRemainingAp());
}
} else if (sub[0].equals("buffme")) {
final int[] array = {9001000, 9101002, 9101003, 9101008, 2001002, 1101007, 1005, 2301003, 5121009, 1111002, 4111001, 4111002, 4211003, 4211005, 1321000, 2321004, 3121002};
for (int i : array) {
SkillFactory.getSkill(i).getEffect(SkillFactory.getSkill(i).getMaxLevel()).applyTo(player);
}
} else if (sub[0].equals("spawn")) {
MapleMonster monster = MapleLifeFactory.getMonster(Integer.parseInt(sub[1]));
if (monster == null) {
return true;
}
if (sub.length > 2) {
for (int i = 0; i < Integer.parseInt(sub[2]); i++) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
}
} else {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(Integer.parseInt(sub[1])), player.getPosition());
}
} else if (sub[0].equals("bomb")) {
if (sub.length > 1){
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), victim.getPosition());
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !bomb on " + victim.getName()));
} else {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9300166), player.getPosition());
}
} else if (sub[0].equals("mutemap")) {
if(player.getMap().isMuted()) {
player.getMap().setMuted(false);
player.dropMessage(5, "The map you are in has been un-muted.");
} else {
player.getMap().setMuted(true);
player.dropMessage(5, "The map you are in has been muted.");
}
} else if (sub[0].equals("checkdmg")) {
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
int maxBase = victim.calculateMaxBaseDamage(victim.getTotalWatk());
Integer watkBuff = victim.getBuffedValue(MapleBuffStat.WATK);
Integer matkBuff = victim.getBuffedValue(MapleBuffStat.MATK);
Integer blessing = victim.getSkillLevel(10000000 * player.getJobType() + 12);
if(watkBuff == null) watkBuff = 0;
if(matkBuff == null) matkBuff = 0;
player.dropMessage(5, "Cur Str: " + victim.getTotalStr() + " Cur Dex: " + victim.getTotalDex() + " Cur Int: " + victim.getTotalInt() + " Cur Luk: " + victim.getTotalLuk());
player.dropMessage(5, "Cur WATK: " + victim.getTotalWatk() + " Cur MATK: " + victim.getTotalMagic());
player.dropMessage(5, "Cur WATK Buff: " + watkBuff + " Cur MATK Buff: " + matkBuff + " Cur Blessing Level: " + blessing);
player.dropMessage(5, victim.getName() + "'s maximum base damage (before skills) is " + maxBase);
} else if (sub[0].equals("inmap")) {
String s = "";
for (MapleCharacter chr : player.getMap().getCharacters()) {
s += chr.getName() + " ";
}
player.message(s);
} else if (sub[0].equals("cleardrops")) {
player.getMap().clearDrops(player);
} else if (sub[0].equals("go")) {
if (gotomaps.containsKey(sub[1])) {
MapleMap target = c.getChannelServer().getMapFactory().getMap(gotomaps.get(sub[1]));
MaplePortal targetPortal = target.getPortal(0);
if (player.getEventInstance() != null) {
player.getEventInstance().removePlayer(player);
}
player.changeMap(target, targetPortal);
} else {
player.dropMessage(5, "That map does not exist.");
}
} else if (sub[0].equals("reloadevents")) {
for (Channel ch : Server.getInstance().getAllChannels()) {
ch.reloadEventScriptManager();
}
player.dropMessage(5, "Reloaded Events");
} else if (sub[0].equals("reloaddrops")) {
MapleMonsterInformationProvider.getInstance().clearDrops();
player.dropMessage(5, "Reloaded Drops");
} else if (sub[0].equals("reloadportals")) {
PortalScriptManager.getInstance().reloadPortalScripts();
player.dropMessage(5, "Reloaded Portals");
} else if (sub[0].equals("whereami")) { //This is so not going to work on the first commit
player.yellowMessage("Map ID: " + player.getMap().getId());
player.yellowMessage("Players on this map:");
for (MapleMapObject mmo : player.getMap().getAllPlayer()) {
MapleCharacter chr = (MapleCharacter) mmo;
player.dropMessage(5, ">> " + chr.getName());
}
player.yellowMessage("NPCs on this map:");
for (MapleMapObject npcs : player.getMap().getMapObjects()) {
if (npcs instanceof MapleNPC) {
MapleNPC npc = (MapleNPC) npcs;
player.dropMessage(5, ">> " + npc.getName() + " - " + npc.getId());
}
}
player.yellowMessage("Monsters on this map:");
for (MapleMapObject mobs : player.getMap().getMapObjects()) {
if (mobs instanceof MapleMonster) {
MapleMonster mob = (MapleMonster) mobs;
if(mob.isAlive()){
player.dropMessage(5, ">> " + mob.getName() + " - " + mob.getId());
}
}
}
} else if (sub[0].equals("warp")) {
try {
MapleMap target = c.getChannelServer().getMapFactory().getMap(Integer.parseInt(sub[1]));
if (target == null) {
player.yellowMessage("Map ID " + sub[1] + " is invalid.");
return false;
}
if (player.getEventInstance() != null) {
player.getEventInstance().removePlayer(player);
}
player.changeMap(target, target.getPortal(0));
} catch (Exception ex) {
ex.printStackTrace();
player.yellowMessage("Map ID " + sub[1] + " is invalid.");
return false;
}
} else if (sub[0].equals("reloadmap")) {
MapleMap oldMap = c.getPlayer().getMap();
MapleMap newMap = c.getChannelServer().getMapFactory().getMap(player.getMapId());
for (MapleCharacter ch : oldMap.getCharacters()) {
ch.changeMap(newMap);
}
oldMap = null;
newMap.respawn();
} else if (sub[0].equals("music")){
if (sub.length < 2) {
player.yellowMessage("Syntax: !music <song>");
for (String s : songs){
player.yellowMessage(s);
}
return false;
}
String song = joinStringFrom(sub, 1);
for (String s : songs){
if (s.equals(song)){
player.getMap().broadcastMessage(MaplePacketCreator.musicChange(s));
player.yellowMessage("Now playing song " + song + ".");
return true;
}
}
player.yellowMessage("Song not found, please enter a song below.");
for (String s : songs){
player.yellowMessage(s);
}
} else if (sub[0].equals("monitor")) {
if (sub.length < 1){
player.yellowMessage("Syntax: !monitor <ign>");
return false;
}
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null){
player.yellowMessage("Player not found!");
return false;
}
boolean monitored = MapleLogger.monitored.contains(victim.getName());
if (monitored){
MapleLogger.monitored.remove(victim.getName());
} else {
MapleLogger.monitored.add(victim.getName());
}
player.yellowMessage(victim.getName() + " is " + (!monitored ? "now being monitored." : "no longer being monitored."));
String message = player.getName() + (!monitored ? " has started monitoring " : " has stopped monitoring ") + victim.getName() + ".";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
} else if (sub[0].equals("monitors")) {
for (String ign : MapleLogger.monitored){
player.yellowMessage(ign + " is being monitored.");
}
} else if (sub[0].equals("ignore")) {
if (sub.length < 1){
player.yellowMessage("Syntax: !ignore <ign>");
return false;
}
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null){
player.yellowMessage("Player not found!");
return false;
}
boolean monitored = MapleLogger.ignored.contains(victim.getName());
if (monitored){
MapleLogger.ignored.remove(victim.getName());
} else {
MapleLogger.ignored.add(victim.getName());
}
player.yellowMessage(victim.getName() + " is " + (!monitored ? "now being ignored." : "no longer being ignored."));
String message = player.getName() + (!monitored ? " has started ignoring " : " has stopped ignoring ") + victim.getName() + ".";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
} else if (sub[0].equals("ignored")) {
for (String ign : MapleLogger.ignored){
player.yellowMessage(ign + " is being ignored.");
}
} else if (sub[0].equals("pos")) {
float xpos = player.getPosition().x;
float ypos = player.getPosition().y;
float fh = player.getMap().getFootholds().findBelow(player.getPosition()).getId();
player.dropMessage("Position: (" + xpos + ", " + ypos + ")");
player.dropMessage("Foothold ID: " + fh);
} else if (sub[0].equals("dc")) {
MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {
victim = player.getMap().getCharacterByName(sub[1]);
if (victim != null) {
try {//sometimes bugged because the map = null
victim.getClient().disconnect(true, false);
player.getMap().removePlayer(victim);
} catch (Exception e) {
e.printStackTrace();
}
} else {
return true;
}
}
}
if (player.gmLevel() < victim.gmLevel()) {
victim = player;
}
victim.getClient().disconnect(false, false);
} else if (sub[0].equals("exprate")) {
c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
} else if (sub[0].equals("chat")) {
player.toggleWhiteChat();
player.message("Your chat is now " + (player.getWhiteChat() ? " white" : "normal") + ".");
} else if (sub[0].equals("warpto")) {
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {//If victim isn't on current channel or isnt a character try and find him by loop all channels on current world.
for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
if (victim != null) {
break;//We found the person, no need to continue the loop.
}
}
}
if (victim != null) {//If target isn't null attempt to warp.
//Remove warper from current event instance.
if (player.getEventInstance() != null) {
player.getEventInstance().unregisterPlayer(player);
}
//Attempt to join the victims warp instance.
if (victim.getEventInstance() != null) {
if (victim.getClient().getChannel() == player.getClient().getChannel()) {//just in case.. you never know...
//victim.getEventInstance().registerPlayer(player);
player.changeMap(victim.getEventInstance().getMapInstance(victim.getMapId()), victim.getMap().findClosestPortal(victim.getPosition()));
} else {
player.dropMessage("Please change to channel " + victim.getClient().getChannel());
}
} else {//If victim isn't in an event instance, just warp them.
player.changeMap(victim.getMapId(), victim.getMap().findClosestPortal(victim.getPosition()));
}
if (player.getClient().getChannel() != victim.getClient().getChannel()) {//And then change channel if needed.
player.dropMessage("Changing channel, please wait a moment.");
player.getClient().changeChannel(victim.getClient().getChannel());
}
} else {
player.dropMessage("Unknown player.");
}
} else if (sub[0].equals("warphere")) {
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
if (victim == null) {//If victim isn't on current channel, loop all channels on current world.
for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
victim = ch.getPlayerStorage().getCharacterByName(sub[1]);
if (victim != null) {
break;//We found the person, no need to continue the loop.
}
}
}
if (victim != null) {
if (victim.getEventInstance() != null) {
victim.getEventInstance().unregisterPlayer(victim);
}
//Attempt to join the warpers instance.
if (player.getEventInstance() != null) {
if (player.getClient().getChannel() == victim.getClient().getChannel()) {//just in case.. you never know...
player.getEventInstance().registerPlayer(victim);
victim.changeMap(player.getEventInstance().getMapInstance(player.getMapId()), player.getMap().findClosestPortal(player.getPosition()));
} else {
player.dropMessage("Target isn't on your channel, not able to warp into event instance.");
}
} else {//If victim isn't in an event instance, just warp them.
victim.changeMap(player.getMapId(), player.getMap().findClosestPortal(player.getPosition()));
}
if (player.getClient().getChannel() != victim.getClient().getChannel()) {//And then change channel if needed.
victim.dropMessage("Changing channel, please wait a moment.");
victim.getClient().changeChannel(player.getClient().getChannel());
}
} else {
player.dropMessage("Unknown player.");
}
} else if (sub[0].equals("fame")) {
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
victim.setFame(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.FAME, victim.getFame());
} else if (sub[0].equals("giftnx")) {
cserv.getPlayerStorage().getCharacterByName(sub[1]).getCashShop().gainCash(1, Integer.parseInt(sub[2]));
player.message("Done");
} else if (sub[0].equals("gmshop")) {
MapleShopFactory.getInstance().getShop(1337).sendShop(c);
} else if (sub[0].equals("heal")) {
player.setHpMp(30000);
} else if (sub[0].equals("vp")) {
c.addVotePoints(Integer.parseInt(sub[1]));
} else if (sub[0].equals("id")) {
try {
try (BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + sub[1] + "&check=true").openConnection().getInputStream()))) {
String s;
while ((s = dis.readLine()) != null) {
player.dropMessage(s);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (sub[0].equals("item") || sub[0].equals("drop")) {
int itemId = Integer.parseInt(sub[1]);
short quantity = 1;
try {
quantity = Short.parseShort(sub[2]);
} catch (Exception e) {
e.printStackTrace();
}
if (sub[0].equals("item")) {
int petid = -1;
if (ItemConstants.isPet(itemId)) {
petid = MaplePet.createPet(itemId);
}
MapleInventoryManipulator.addById(c, itemId, quantity, player.getName(), petid, -1);
} else {
Item toDrop;
if (MapleItemInformationProvider.getInstance().getInventoryType(itemId) == MapleInventoryType.EQUIP) {
toDrop = MapleItemInformationProvider.getInstance().getEquipById(itemId);
} else {
toDrop = new Item(itemId, (short) 0, quantity);
}
c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
}
} else if (sub[0].equals("expeds")) {
for (Channel ch : Server.getInstance().getChannelsFromWorld(0)) {
if (ch.getExpeditions().size() == 0) {
player.yellowMessage("No Expeditions in Channel " + ch.getId());
continue;
}
player.yellowMessage("Expeditions in Channel " + ch.getId());
int id = 0;
for (MapleExpedition exped : ch.getExpeditions()) {
id++;
player.yellowMessage("> Expedition " + id);
player.yellowMessage(">> Type: " + exped.getType().toString());
player.yellowMessage(">> Status: " + (exped.isRegistering() ? "REGISTERING" : "UNDERWAY"));
player.yellowMessage(">> Size: " + exped.getMembers().size());
player.yellowMessage(">> Leader: " + exped.getLeader().getName());
int memId = 2;
for (MapleCharacter member : exped.getMembers()) {
if (exped.isLeader(member)) {
continue;
}
player.yellowMessage(">>> Member " + memId + ": " + member.getName());
memId++;
}
}
}
} else if (sub[0].equals("kill")) {
if (sub.length >= 2) {
MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
victim.setHpMp(0);
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !kill on " + victim.getName()));
}
} else if (sub[0].equals("seed")) {
if (player.getMapId() != 910010000) {
player.yellowMessage("This command can only be used in HPQ.");
return false;
}
Point pos[] = {new Point(7, -207), new Point(179, -447), new Point(-3, -687), new Point(-357, -687), new Point(-538, -447), new Point(-359, -207)};
int seed[] = {4001097, 4001096, 4001095, 4001100, 4001099, 4001098};
for (int i = 0; i < pos.length; i++) {
Item item = new Item(seed[i], (byte) 0, (short) 1);
player.getMap().spawnItemDrop(player, player, item, pos[i], false, true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else if (sub[0].equals("killall")) {
List<MapleMapObject> monsters = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
MapleMap map = player.getMap();
for (MapleMapObject monstermo : monsters) {
MapleMonster monster = (MapleMonster) monstermo;
if (!monster.getStats().isFriendly()) {
map.killMonster(monster, player, true);
monster.giveExpToCharacter(player, monster.getExp() * c.getPlayer().getExpRate(), true, 1);
}
}
player.dropMessage("Killed " + monsters.size() + " monsters.");
} else if (sub[0].equals("monsterdebug")) {
List<MapleMapObject> monsters = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
for (MapleMapObject monstermo : monsters) {
MapleMonster monster = (MapleMonster) monstermo;
player.message("Monster ID: " + monster.getId());
}
} else if (sub[0].equals("unbug")) {
c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.enableActions());
} else if (sub[0].equals("level")) {
player.setLevel(Integer.parseInt(sub[1]) - 1);
player.gainExp(-player.getExp(), false, false);
player.levelUp(false);
} else if (sub[0].equals("levelpro")) {
while (player.getLevel() < Math.min(255, Integer.parseInt(sub[1]))) {
player.levelUp(false);
}
} else if (sub[0].equals("maxstat")) {
final String[] s = {"setall", String.valueOf(Short.MAX_VALUE)};
executeGMCommand(c, s, heading);
player.setLevel(255);
player.setFame(13337);
player.setMaxHp(30000);
player.setMaxMp(30000);
player.updateSingleStat(MapleStat.LEVEL, 255);
player.updateSingleStat(MapleStat.FAME, 13337);
player.updateSingleStat(MapleStat.MAXHP, 30000);
player.updateSingleStat(MapleStat.MAXMP, 30000);
} else if (sub[0].equals("maxskills")) {
for (MapleData skill_ : MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/" + "String.wz")).getData("Skill.img").getChildren()) {
try {
Skill skill = SkillFactory.getSkill(Integer.parseInt(skill_.getName()));
if (GameConstants.isInJobTree(skill.getId(), player.getJob().getId())) {
player.changeSkillLevel(skill, (byte) skill.getMaxLevel(), skill.getMaxLevel(), -1);
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
break;
} catch (NullPointerException npe) {
npe.printStackTrace();
continue;
}
}
} else if (sub[0].equals("mesos")) {
player.gainMeso(Integer.parseInt(sub[1]), true);
} else if (sub[0].equals("notice")) {
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[Notice] " + joinStringFrom(sub, 1)));
} else if (sub[0].equals("rip")) {
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + joinStringFrom(sub, 1)));
} else if (sub[0].equals("openportal")) {
player.getMap().getPortal(sub[1]).setPortalState(true);
} else if (sub[0].equals("pe")) {
String packet = "";
try {
InputStreamReader is = new FileReader("pe.txt");
Properties packetProps = new Properties();
packetProps.load(is);
is.close();
packet = packetProps.getProperty("pe");
} catch (IOException ex) {
ex.printStackTrace();
player.yellowMessage("Failed to load pe.txt");
return false;
}
MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter();
mplew.write(HexTool.getByteArrayFromHexString(packet));
SeekableLittleEndianAccessor slea = new GenericSeekableLittleEndianAccessor(new ByteArrayByteStream(mplew.getPacket()));
short packetId = slea.readShort();
final MaplePacketHandler packetHandler = PacketProcessor.getProcessor(0, c.getChannel()).getHandler(packetId);
if (packetHandler != null && packetHandler.validateState(c)) {
try {
player.yellowMessage("Recieving: " + packet);
packetHandler.handlePacket(slea, c);
} catch (final Throwable t) {
FilePrinter.printError(FilePrinter.PACKET_HANDLER + packetHandler.getClass().getName() + ".txt", t, "Error for " + (c.getPlayer() == null ? "" : "player ; " + c.getPlayer() + " on map ; " + c.getPlayer().getMapId() + " - ") + "account ; " + c.getAccountName() + "\r\n" + slea.toString());
return false;
}
}
} else if (sub[0].equals("closeportal")) {
player.getMap().getPortal(sub[1]).setPortalState(false);
} else if (sub[0].equals("startevent")) {
for (MapleCharacter chr : player.getMap().getCharacters()) {
player.getMap().startEvent(chr);
}
c.getChannelServer().setEvent(null);
} else if (sub[0].equals("scheduleevent")) {
int players = 50;
if(sub.length > 1)
players = Integer.parseInt(sub[1]);
c.getChannelServer().setEvent(new MapleEvent(player.getMapId(), players));
player.dropMessage(5, "The event has been set on " + player.getMap().getMapName() + " and will allow " + players + " players to join.");
} else if(sub[0].equals("endevent")) {
c.getChannelServer().setEvent(null);
player.dropMessage(5, "You have ended the event. No more players may join.");
} else if (sub[0].equals("online2")) {
int total = 0;
for (Channel ch : srv.getChannelsFromWorld(player.getWorld())) {
int size = ch.getPlayerStorage().getAllCharacters().size();
total += size;
String s = "(Channel " + ch.getId() + " Online: " + size + ") : ";
if (ch.getPlayerStorage().getAllCharacters().size() < 50) {
for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
}
player.dropMessage(s.substring(0, s.length() - 2));
}
}
player.dropMessage("There are a total of " + total + " players online.");
} else if (sub[0].equals("pap")) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8500001), player.getPosition());
} else if (sub[0].equals("pianus")) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8510000), player.getPosition());
} else if (sub[0].equalsIgnoreCase("search")) {
StringBuilder sb = new StringBuilder();
if (sub.length > 2) {
String search = joinStringFrom(sub, 2);
long start = System.currentTimeMillis();//for the lulz
MapleData data = null;
MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
if (!sub[1].equalsIgnoreCase("ITEM")) {
if (sub[1].equalsIgnoreCase("NPC")) {
data = dataProvider.getData("Npc.img");
} else if (sub[1].equalsIgnoreCase("MOB") || sub[1].equalsIgnoreCase("MONSTER")) {
data = dataProvider.getData("Mob.img");
} else if (sub[1].equalsIgnoreCase("SKILL")) {
data = dataProvider.getData("Skill.img");
} else if (sub[1].equalsIgnoreCase("MAP")) {
sb.append("#bUse the '/m' command to find a map. If it finds a map with the same name, it will warp you to it.");
} else {
sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
}
if (data != null) {
String name;
for (MapleData searchData : data.getChildren()) {
name = MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
if (name.toLowerCase().contains(search.toLowerCase())) {
sb.append("#b").append(Integer.parseInt(searchData.getName())).append("#k - #r").append(name).append("\r\n");
}
}
}
} else {
for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
if (sb.length() < 32654) {//ohlol
if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
//#v").append(id).append("# #k-
sb.append("#b").append(itemPair.getLeft()).append("#k - #r").append(itemPair.getRight()).append("\r\n");
}
} else {
sb.append("#bCouldn't load all items, there are too many results.\r\n");
break;
}
}
}
if (sb.length() == 0) {
sb.append("#bNo ").append(sub[1].toLowerCase()).append("s found.\r\n");
}
sb.append("\r\n#kLoaded within ").append((double) (System.currentTimeMillis() - start) / 1000).append(" seconds.");//because I can, and it's free
} else {
sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
}
c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, sb.toString(), "00 00", (byte) 0));
} else if (sub[0].equals("servermessage")) {
c.getWorldServer().setServerMessage(joinStringFrom(sub, 1));
} else if (sub[0].equals("warpsnowball")) {
List<MapleCharacter> chars = new ArrayList<>(player.getMap().getCharacters());
for (MapleCharacter chr : chars) {
chr.changeMap(109060000, chr.getTeam());
}
} else if (sub[0].equals("setall")) {
final int x = Short.parseShort(sub[1]);
player.setStr(x);
player.setDex(x);
player.setInt(x);
player.setLuk(x);
player.updateSingleStat(MapleStat.STR, x);
player.updateSingleStat(MapleStat.DEX, x);
player.updateSingleStat(MapleStat.INT, x);
player.updateSingleStat(MapleStat.LUK, x);
} else if (sub[0].equals("unban")) {
try {
Connection con = DatabaseConnection.getConnection();
int aid = MapleCharacter.getAccountIdByName(sub[1]);
PreparedStatement p = con.prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + aid);
p.executeUpdate();
p = con.prepareStatement("DELETE FROM ipbans WHERE aid = " + aid);
p.executeUpdate();
p = con.prepareStatement("DELETE FROM macbans WHERE aid = " + aid);
p.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
player.message("Failed to unban " + sub[1]);
return true;
}
player.message("Unbanned " + sub[1]);
} else if (sub[0].equals("ban")) {
if (sub.length < 3) {
player.yellowMessage("Syntax: !ban <IGN> <Reason> (Please be descriptive)");
return false;
}
String ign = sub[1];
String reason = joinStringFrom(sub, 2);
MapleCharacter target = c.getChannelServer().getPlayerStorage().getCharacterByName(ign);
if (target != null) {
String readableTargetName = MapleCharacter.makeMapleReadable(target.getName());
String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0];
//Ban ip
PreparedStatement ps = null;
try {
Connection con = DatabaseConnection.getConnection();
if (ip.matches("/[0-9]{1,3}\\..*")) {
ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?, ?)");
ps.setString(1, ip);
ps.setString(2, String.valueOf(target.getClient().getAccID()));
ps.executeUpdate();
ps.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
c.getPlayer().message("Error occured while banning IP address");
c.getPlayer().message(target.getName() + "'s IP was not banned: " + ip);
}
target.getClient().banMacs();
reason = c.getPlayer().getName() + " banned " + readableTargetName + " for " + reason + " (IP: " + ip + ") " + "(MAC: " + c.getMacs() + ")";
target.ban(reason);
target.yellowMessage("You have been banned by #b" + c.getPlayer().getName() + " #k.");
target.yellowMessage("Reason: " + reason);
c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
final MapleCharacter rip = target;
TimerManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
rip.getClient().disconnect(false, false);
}
}, 5000); //5 Seconds
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
} else if (MapleCharacter.ban(ign, reason, false)) {
c.announce(MaplePacketCreator.getGMEffect(4, (byte) 0));
Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + ign + " has been banned."));
} else {
c.announce(MaplePacketCreator.getGMEffect(6, (byte) 1));
}
} else if (sub[0].equalsIgnoreCase("night")) {
player.getMap().broadcastNightEffect();
player.yellowMessage("Done.");
} else {
return false;
}
return true;
}
public static void executeAdminCommand(MapleClient c, String[] sub, char heading) {
MapleCharacter player = c.getPlayer();
switch (sub[0]) {
case "sp": //Changed to support giving sp /a
if (sub.length == 2) {
player.setRemainingSp(Integer.parseInt(sub[1]));
player.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
} else {
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.setRemainingSp(Integer.parseInt(sub[2]));
victim.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
}
break;
case "horntail":
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8810026), player.getPosition());
break;
case "packet":
player.getMap().broadcastMessage(MaplePacketCreator.customPacket(joinStringFrom(sub, 1)));
break;
case "timerdebug":
TimerManager tMan = TimerManager.getInstance();
player.dropMessage(6, "Total Task: " + tMan.getTaskCount() + " Current Task: " + tMan.getQueuedTasks() + " Active Task: " + tMan.getActiveCount() + " Completed Task: " + tMan.getCompletedTaskCount());
break;
case "warpworld":
Server server = Server.getInstance();
byte worldb = Byte.parseByte(sub[1]);
if (worldb <= (server.getWorlds().size() - 1)) {
try {
String[] socket = server.getIP(worldb, c.getChannel()).split(":");
c.getWorldServer().removePlayer(player);
player.getMap().removePlayer(player);//LOL FORGOT THIS ><
c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
player.setWorld(worldb);
player.saveToDB();//To set the new world :O (true because else 2 player instances are created, one in both worlds)
c.announce(MaplePacketCreator.getChannelChange(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1])));
} catch (UnknownHostException | NumberFormatException ex) {
ex.printStackTrace();
player.message("Error when trying to change worlds, are you sure the world you are trying to warp to has the same amount of channels?");
}
} else {
player.message("Invalid world; highest number available: " + (server.getWorlds().size() - 1));
}
break;
case "saveall"://fyi this is a stupid command
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
chr.saveToDB();
}
}
String message = player.getName() + " used !saveall.";
Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, message));
player.message("All players saved successfully.");
break;
case "dcall":
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
if (!chr.isGM()) {
chr.getClient().disconnect(false, false);
}
}
}
player.message("All players successfully disconnected.");
break;
case "mapplayers"://fyi this one is even stupider
//Adding HP to it, making it less useless.
String names = "";
int map = player.getMapId();
for (World world : Server.getInstance().getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
int curMap = chr.getMapId();
String hp = Integer.toString(chr.getHp());
String maxhp = Integer.toString(chr.getMaxHp());
String name = chr.getName() + ": " + hp + "/" + maxhp;
if (map == curMap) {
names = names.equals("") ? name : (names + ", " + name);
}
}
}
player.message("These b lurkin: " + names);
break;
case "getacc":
if (sub.length < 1) {
player.message("Please provide an IGN.");
break;
}
MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.message(victim.getName() + "'s account name is " + victim.getClient().getAccountName() + ".");
break;
case "npc":
if (sub.length < 1) {
break;
}
MapleNPC npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
if (npc != null) {
npc.setPosition(player.getPosition());
npc.setCy(player.getPosition().y);
npc.setRx0(player.getPosition().x + 50);
npc.setRx1(player.getPosition().x - 50);
npc.setFh(player.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
player.getMap().addMapObject(npc);
player.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
}
break;
case "job": { //Honestly, we should merge this with @job and job yourself if array is 1 long only. I'll do it but gotta run at this point lel
//Alright, doing that. /a
if (sub.length == 2) {
player.changeJob(MapleJob.getById(Integer.parseInt(sub[1])));
player.equipChanged();
} else if (sub.length == 3) {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
victim.changeJob(MapleJob.getById(Integer.parseInt(sub[2])));
player.equipChanged();
} else {
player.message("!job <job id> <opt: IGN of another person>");
}
break;
}
case "playernpc":
player.playerNPC(c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]), Integer.parseInt(sub[2]));
break;
case "shutdown":
case "shutdownnow":
int time = 60000;
if (sub[0].equals("shutdownnow")) {
time = 1;
} else if (sub.length > 1) {
time *= Integer.parseInt(sub[1]);
}
TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
break;
case "face":
if (sub.length == 2) {
player.setFace(Integer.parseInt(sub[1]));
player.equipChanged();
} else {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.setFace(Integer.parseInt(sub[2]));
player.equipChanged();
}
break;
case "hair":
if (sub.length == 2) {
player.setHair(Integer.parseInt(sub[1]));
player.equipChanged();
} else {
victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
player.setHair(Integer.parseInt(sub[2]));
player.equipChanged();
}
break;
case "itemvac":
List<MapleMapObject> items = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.ITEM));
for (MapleMapObject item : items) {
MapleMapItem mapitem = (MapleMapItem) item;
if (!MapleInventoryManipulator.addFromDrop(c, mapitem.getItem(), true)) {
continue;
}
mapitem.setPickedUp(true);
player.getMap().broadcastMessage(MaplePacketCreator.removeItemFromMap(mapitem.getObjectId(), 2, player.getId()), mapitem.getPosition());
player.getMap().removeMapObject(item);
}
break;
case "zakum":
player.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), player.getPosition());
for (int x = 8800003; x < 8800011; x++) {
player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(x), player.getPosition());
}
break;
case "clearquestcache":
MapleQuest.clearCache();
player.dropMessage(5, "Quest Cache Cleared.");
break;
case "clearquest":
if(sub.length < 1) {
player.dropMessage(5, "Plese include a quest ID.");
return;
}
MapleQuest.clearCache(Integer.parseInt(sub[1]));
player.dropMessage(5, "Quest Cache for quest " + sub[1] + " cleared.");
break;
default:
player.yellowMessage("Command " + heading + sub[0] + " does not exist.");
break;
}
}
private static String joinStringFrom(String arr[], int start) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
builder.append(arr[i]);
if (i != arr.length - 1) {
builder.append(" ");
}
}
return builder.toString();
}
}
| Small patch with commands
Added usage info for some commands in the game.
| src/client/command/Commands.java | Small patch with commands | <ide><path>rc/client/command/Commands.java
<ide> SkillFactory.getSkill(i).getEffect(SkillFactory.getSkill(i).getMaxLevel()).applyTo(player);
<ide> }
<ide> } else if (sub[0].equals("spawn")) {
<add> if (sub.length < 2) {
<add> player.yellowMessage("Syntax: !spawn <mobid>");
<add> return false;
<add> }
<add>
<ide> MapleMonster monster = MapleLifeFactory.getMonster(Integer.parseInt(sub[1]));
<ide> if (monster == null) {
<ide> return true;
<ide> } else if (sub[0].equals("cleardrops")) {
<ide> player.getMap().clearDrops(player);
<ide> } else if (sub[0].equals("go")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !spawn <mobid>");
<add> return false;
<add> }
<add>
<ide> if (gotomaps.containsKey(sub[1])) {
<ide> MapleMap target = c.getChannelServer().getMapFactory().getMap(gotomaps.get(sub[1]));
<ide> MaplePortal targetPortal = target.getPortal(0);
<ide> }
<ide> }
<ide> } else if (sub[0].equals("warp")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !warp <mapid>");
<add> return false;
<add> }
<add>
<ide> try {
<ide> MapleMap target = c.getChannelServer().getMapFactory().getMap(Integer.parseInt(sub[1]));
<ide> if (target == null) {
<ide> player.dropMessage("Position: (" + xpos + ", " + ypos + ")");
<ide> player.dropMessage("Foothold ID: " + fh);
<ide> } else if (sub[0].equals("dc")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !dc <playername>");
<add> return false;
<add> }
<add>
<ide> MapleCharacter victim = c.getWorldServer().getPlayerStorage().getCharacterByName(sub[1]);
<ide> if (victim == null) {
<ide> victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
<ide> }
<ide> victim.getClient().disconnect(false, false);
<ide> } else if (sub[0].equals("exprate")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !exprate <newrate>");
<add> return false;
<add> }
<ide> c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
<ide> } else if (sub[0].equals("chat")) {
<ide> player.toggleWhiteChat();
<ide> player.message("Your chat is now " + (player.getWhiteChat() ? " white" : "normal") + ".");
<ide> } else if (sub[0].equals("warpto")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !warpto <mapid>");
<add> return false;
<add> }
<add>
<ide> MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
<ide> if (victim == null) {//If victim isn't on current channel or isnt a character try and find him by loop all channels on current world.
<ide> for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
<ide> player.dropMessage("Unknown player.");
<ide> }
<ide> } else if (sub[0].equals("warphere")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !warphere <playername>");
<add> return false;
<add> }
<add>
<ide> MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
<ide> if (victim == null) {//If victim isn't on current channel, loop all channels on current world.
<ide> for (Channel ch : srv.getChannelsFromWorld(c.getWorld())) {
<ide> player.dropMessage("Unknown player.");
<ide> }
<ide> } else if (sub[0].equals("fame")) {
<add> if (sub.length < 3){
<add> player.yellowMessage("Syntax: !fame <playername> <gainfame>");
<add> return false;
<add> }
<add>
<ide> MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
<ide> victim.setFame(Integer.parseInt(sub[2]));
<ide> victim.updateSingleStat(MapleStat.FAME, victim.getFame());
<ide> } else if (sub[0].equals("giftnx")) {
<add> if (sub.length < 3){
<add> player.yellowMessage("Syntax: !giftnx <playername> <gainnx>");
<add> return false;
<add> }
<ide> cserv.getPlayerStorage().getCharacterByName(sub[1]).getCashShop().gainCash(1, Integer.parseInt(sub[2]));
<ide> player.message("Done");
<ide> } else if (sub[0].equals("gmshop")) {
<ide> } else if (sub[0].equals("heal")) {
<ide> player.setHpMp(30000);
<ide> } else if (sub[0].equals("vp")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !vp <gainvotepoint>");
<add> return false;
<add> }
<ide> c.addVotePoints(Integer.parseInt(sub[1]));
<ide> } else if (sub[0].equals("id")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !id <id>");
<add> return false;
<add> }
<ide> try {
<ide> try (BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + sub[1] + "&check=true").openConnection().getInputStream()))) {
<ide> String s;
<ide> e.printStackTrace();
<ide> }
<ide> } else if (sub[0].equals("item") || sub[0].equals("drop")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !item <itemid> <quantity>");
<add> return false;
<add> }
<add>
<ide> int itemId = Integer.parseInt(sub[1]);
<add>
<ide> short quantity = 1;
<del> try {
<del> quantity = Short.parseShort(sub[2]);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> if(sub.length >= 3) quantity = Short.parseShort(sub[2]);
<add>
<ide> if (sub[0].equals("item")) {
<ide> int petid = -1;
<ide> if (ItemConstants.isPet(itemId)) {
<ide> }
<ide> }
<ide> } else if (sub[0].equals("kill")) {
<del> if (sub.length >= 2) {
<del> MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
<del> victim.setHpMp(0);
<del> Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !kill on " + victim.getName()));
<del> }
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !kill <playername>");
<add> return false;
<add> }
<add>
<add> MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
<add> victim.setHpMp(0);
<add> Server.getInstance().broadcastGMMessage(MaplePacketCreator.serverNotice(5, player.getName() + " used !kill on " + victim.getName()));
<ide> } else if (sub[0].equals("seed")) {
<ide> if (player.getMapId() != 910010000) {
<ide> player.yellowMessage("This command can only be used in HPQ.");
<ide> } else if (sub[0].equals("unbug")) {
<ide> c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.enableActions());
<ide> } else if (sub[0].equals("level")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !level <newlevel>");
<add> return false;
<add> }
<add>
<ide> player.setLevel(Integer.parseInt(sub[1]) - 1);
<ide> player.gainExp(-player.getExp(), false, false);
<ide> player.levelUp(false);
<ide> } else if (sub[0].equals("levelpro")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !levelpro <newlevel>");
<add> return false;
<add> }
<add>
<ide> while (player.getLevel() < Math.min(255, Integer.parseInt(sub[1]))) {
<ide> player.levelUp(false);
<ide> }
<ide> }
<ide> }
<ide> } else if (sub[0].equals("mesos")) {
<del> player.gainMeso(Integer.parseInt(sub[1]), true);
<add> if (sub.length >= 2) {
<add> player.gainMeso(Integer.parseInt(sub[1]), true);
<add> }
<ide> } else if (sub[0].equals("notice")) {
<ide> Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[Notice] " + joinStringFrom(sub, 1)));
<ide> } else if (sub[0].equals("rip")) {
<ide> Server.getInstance().broadcastMessage(MaplePacketCreator.serverNotice(6, "[RIP]: " + joinStringFrom(sub, 1)));
<ide> } else if (sub[0].equals("openportal")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !openportal <portalid>");
<add> return false;
<add> }
<ide> player.getMap().getPortal(sub[1]).setPortalState(true);
<ide> } else if (sub[0].equals("pe")) {
<ide> String packet = "";
<ide> }
<ide> }
<ide> } else if (sub[0].equals("closeportal")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !closeportal <portalid>");
<add> return false;
<add> }
<ide> player.getMap().getPortal(sub[1]).setPortalState(false);
<ide> } else if (sub[0].equals("startevent")) {
<ide> for (MapleCharacter chr : player.getMap().getCharacters()) {
<ide> } else if (sub[0].equals("pianus")) {
<ide> player.getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8510000), player.getPosition());
<ide> } else if (sub[0].equalsIgnoreCase("search")) {
<add> if (sub.length < 3){
<add> player.yellowMessage("Syntax: !search <type> <name>");
<add> return false;
<add> }
<add>
<ide> StringBuilder sb = new StringBuilder();
<del> if (sub.length > 2) {
<del> String search = joinStringFrom(sub, 2);
<del> long start = System.currentTimeMillis();//for the lulz
<del> MapleData data = null;
<del> MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
<del> if (!sub[1].equalsIgnoreCase("ITEM")) {
<del> if (sub[1].equalsIgnoreCase("NPC")) {
<del> data = dataProvider.getData("Npc.img");
<del> } else if (sub[1].equalsIgnoreCase("MOB") || sub[1].equalsIgnoreCase("MONSTER")) {
<del> data = dataProvider.getData("Mob.img");
<del> } else if (sub[1].equalsIgnoreCase("SKILL")) {
<del> data = dataProvider.getData("Skill.img");
<del> } else if (sub[1].equalsIgnoreCase("MAP")) {
<del> sb.append("#bUse the '/m' command to find a map. If it finds a map with the same name, it will warp you to it.");
<del> } else {
<del> sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
<del> }
<del> if (data != null) {
<del> String name;
<del> for (MapleData searchData : data.getChildren()) {
<del> name = MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
<del> if (name.toLowerCase().contains(search.toLowerCase())) {
<del> sb.append("#b").append(Integer.parseInt(searchData.getName())).append("#k - #r").append(name).append("\r\n");
<del> }
<del> }
<del> }
<del> } else {
<del> for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
<del> if (sb.length() < 32654) {//ohlol
<del> if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
<del> //#v").append(id).append("# #k-
<del> sb.append("#b").append(itemPair.getLeft()).append("#k - #r").append(itemPair.getRight()).append("\r\n");
<del> }
<del> } else {
<del> sb.append("#bCouldn't load all items, there are too many results.\r\n");
<del> break;
<del> }
<del> }
<del> }
<del> if (sb.length() == 0) {
<del> sb.append("#bNo ").append(sub[1].toLowerCase()).append("s found.\r\n");
<del> }
<del> sb.append("\r\n#kLoaded within ").append((double) (System.currentTimeMillis() - start) / 1000).append(" seconds.");//because I can, and it's free
<del> } else {
<del> sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
<del> }
<add>
<add> String search = joinStringFrom(sub, 2);
<add> long start = System.currentTimeMillis();//for the lulz
<add> MapleData data = null;
<add> MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
<add> if (!sub[1].equalsIgnoreCase("ITEM")) {
<add> if (sub[1].equalsIgnoreCase("NPC")) {
<add> data = dataProvider.getData("Npc.img");
<add> } else if (sub[1].equalsIgnoreCase("MOB") || sub[1].equalsIgnoreCase("MONSTER")) {
<add> data = dataProvider.getData("Mob.img");
<add> } else if (sub[1].equalsIgnoreCase("SKILL")) {
<add> data = dataProvider.getData("Skill.img");
<add> } else if (sub[1].equalsIgnoreCase("MAP")) {
<add> sb.append("#bUse the '/m' command to find a map. If it finds a map with the same name, it will warp you to it.");
<add> } else {
<add> sb.append("#bInvalid search.\r\nSyntax: '/search [type] [name]', where [type] is NPC, ITEM, MOB, or SKILL.");
<add> }
<add> if (data != null) {
<add> String name;
<add> for (MapleData searchData : data.getChildren()) {
<add> name = MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
<add> if (name.toLowerCase().contains(search.toLowerCase())) {
<add> sb.append("#b").append(Integer.parseInt(searchData.getName())).append("#k - #r").append(name).append("\r\n");
<add> }
<add> }
<add> }
<add> } else {
<add> for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
<add> if (sb.length() < 32654) {//ohlol
<add> if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
<add> //#v").append(id).append("# #k-
<add> sb.append("#b").append(itemPair.getLeft()).append("#k - #r").append(itemPair.getRight()).append("\r\n");
<add> }
<add> } else {
<add> sb.append("#bCouldn't load all items, there are too many results.\r\n");
<add> break;
<add> }
<add> }
<add> }
<add> if (sb.length() == 0) {
<add> sb.append("#bNo ").append(sub[1].toLowerCase()).append("s found.\r\n");
<add> }
<add> sb.append("\r\n#kLoaded within ").append((double) (System.currentTimeMillis() - start) / 1000).append(" seconds.");//because I can, and it's free
<add>
<ide> c.announce(MaplePacketCreator.getNPCTalk(9010000, (byte) 0, sb.toString(), "00 00", (byte) 0));
<ide> } else if (sub[0].equals("servermessage")) {
<ide> c.getWorldServer().setServerMessage(joinStringFrom(sub, 1));
<ide> player.updateSingleStat(MapleStat.INT, x);
<ide> player.updateSingleStat(MapleStat.LUK, x);
<ide> } else if (sub[0].equals("unban")) {
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !unban <playername>");
<add> return false;
<add> }
<add>
<ide> try {
<ide> Connection con = DatabaseConnection.getConnection();
<ide> int aid = MapleCharacter.getAccountIdByName(sub[1]);
<ide> MapleCharacter player = c.getPlayer();
<ide> switch (sub[0]) {
<ide> case "sp": //Changed to support giving sp /a
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !sp <newsp>");
<add> return;
<add> }
<add>
<ide> if (sub.length == 2) {
<ide> player.setRemainingSp(Integer.parseInt(sub[1]));
<ide> player.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
<ide> player.dropMessage(6, "Total Task: " + tMan.getTaskCount() + " Current Task: " + tMan.getQueuedTasks() + " Active Task: " + tMan.getActiveCount() + " Completed Task: " + tMan.getCompletedTaskCount());
<ide> break;
<ide> case "warpworld":
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !warpworld <worldid>");
<add> return;
<add> }
<add>
<ide> Server server = Server.getInstance();
<ide> byte worldb = Byte.parseByte(sub[1]);
<ide> if (worldb <= (server.getWorlds().size() - 1)) {
<ide> player.message("These b lurkin: " + names);
<ide> break;
<ide> case "getacc":
<del> if (sub.length < 1) {
<del> player.message("Please provide an IGN.");
<del> break;
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !getacc <playername>");
<add> return;
<ide> }
<ide> MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]);
<ide> player.message(victim.getName() + "'s account name is " + victim.getClient().getAccountName() + ".");
<ide> break;
<ide> case "npc":
<del> if (sub.length < 1) {
<del> break;
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !npc <npcid>");
<add> return;
<ide> }
<ide> MapleNPC npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
<ide> if (npc != null) {
<ide> break;
<ide> }
<ide> case "playernpc":
<add> if (sub.length < 3){
<add> player.yellowMessage("Syntax: !playernpc <playername> <npcid>");
<add> return;
<add> }
<ide> player.playerNPC(c.getChannelServer().getPlayerStorage().getCharacterByName(sub[1]), Integer.parseInt(sub[2]));
<ide> break;
<ide> case "shutdown":
<ide> TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
<ide> break;
<ide> case "face":
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !face <faceid>");
<add> return;
<add> }
<add>
<ide> if (sub.length == 2) {
<ide> player.setFace(Integer.parseInt(sub[1]));
<ide> player.equipChanged();
<ide> }
<ide> break;
<ide> case "hair":
<add> if (sub.length < 2){
<add> player.yellowMessage("Syntax: !hair <hairid>");
<add> return;
<add> }
<add>
<ide> if (sub.length == 2) {
<ide> player.setHair(Integer.parseInt(sub[1]));
<ide> player.equipChanged(); |
|
Java | bsd-3-clause | f99212c17ae85830f2905c3f2f95f6a3405f0b57 | 0 | skadistats/clarity | package skadistats.clarity.processor.entities;
import com.google.protobuf.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import skadistats.clarity.decoder.FieldReader;
import skadistats.clarity.decoder.Util;
import skadistats.clarity.decoder.bitstream.BitStream;
import skadistats.clarity.event.Event;
import skadistats.clarity.event.Insert;
import skadistats.clarity.event.InsertEvent;
import skadistats.clarity.event.Provides;
import skadistats.clarity.model.DTClass;
import skadistats.clarity.model.EngineType;
import skadistats.clarity.model.Entity;
import skadistats.clarity.model.StringTable;
import skadistats.clarity.processor.reader.OnMessage;
import skadistats.clarity.processor.reader.OnReset;
import skadistats.clarity.processor.reader.ResetPhase;
import skadistats.clarity.processor.runner.OnInit;
import skadistats.clarity.processor.sendtables.DTClasses;
import skadistats.clarity.processor.sendtables.UsesDTClasses;
import skadistats.clarity.processor.stringtables.OnStringTableEntry;
import skadistats.clarity.util.Predicate;
import skadistats.clarity.util.SimpleIterator;
import skadistats.clarity.wire.common.proto.Demo;
import skadistats.clarity.wire.common.proto.NetMessages;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Provides({ UsesEntities.class, OnEntityCreated.class, OnEntityUpdated.class, OnEntityDeleted.class, OnEntityEntered.class, OnEntityLeft.class, OnEntityUpdatesCompleted.class })
@UsesDTClasses
public class Entities {
private static final Logger log = LoggerFactory.getLogger(Entities.class);
private final Map<Integer, BaselineEntry> baselineEntries = new HashMap<>();
private Entity[] entities;
private int[] deletions;
private FieldReader fieldReader;
@Insert
private EngineType engineType;
@Insert
private DTClasses dtClasses;
@InsertEvent
private Event<OnEntityCreated> evCreated;
@InsertEvent
private Event<OnEntityUpdated> evUpdated;
@InsertEvent
private Event<OnEntityDeleted> evDeleted;
@InsertEvent
private Event<OnEntityEntered> evEntered;
@InsertEvent
private Event<OnEntityLeft> evLeft;
@InsertEvent
private Event<OnEntityUpdatesCompleted> evUpdatesCompleted;
private class BaselineEntry {
private ByteString rawBaseline;
private Object[] baseline;
public BaselineEntry(ByteString rawBaseline) {
this.rawBaseline = rawBaseline;
this.baseline = null;
}
}
@OnInit
public void onInitRun() {
fieldReader = engineType.getNewFieldReader();
entities = new Entity[1 << engineType.getIndexBits()];
deletions = new int[1 << engineType.getIndexBits()];
}
@OnReset
public void onReset(Demo.CDemoStringTables packet, ResetPhase phase) {
if (phase == ResetPhase.CLEAR) {
baselineEntries.clear();
for (int entityIndex = 0; entityIndex < entities.length; entityIndex++) {
entities[entityIndex] = null;
}
}
}
@OnStringTableEntry("instancebaseline")
public void onBaselineEntry(StringTable table, int index, String key, ByteString value) {
baselineEntries.put(Integer.valueOf(key), new BaselineEntry(value));
}
@OnMessage(NetMessages.CSVCMsg_PacketEntities.class)
public void onPacketEntities(NetMessages.CSVCMsg_PacketEntities message) {
BitStream stream = BitStream.createBitStream(message.getEntityData());
int updateCount = message.getUpdatedEntries();
int entityIndex = -1;
int cmd;
int clsId;
DTClass cls;
int serial;
Object[] state;
Entity entity;
boolean debug = false;
while (updateCount-- != 0) {
entityIndex += stream.readUBitVar() + 1;
cmd = stream.readUBitInt(2);
if ((cmd & 1) == 0) {
if ((cmd & 2) != 0) {
clsId = stream.readUBitInt(dtClasses.getClassBits());
cls = dtClasses.forClassId(clsId);
if (cls == null) {
throw new RuntimeException(String.format("class for new entity %d is %d, but no dtClass found!.", entityIndex, clsId));
}
serial = stream.readUBitInt(engineType.getSerialBits());
if (engineType == EngineType.SOURCE2) {
// TODO: there is an extra VarInt encoded here for S2, figure out what it is
stream.readVarUInt();
}
state = Util.clone(getBaseline(cls.getClassId()));
fieldReader.readFields(stream, cls, state, debug);
entity = new Entity(engineType, entityIndex, serial, cls, true, state);
entities[entityIndex] = entity;
evCreated.raise(entity);
evEntered.raise(entity);
} else {
entity = entities[entityIndex];
if (entity == null) {
throw new RuntimeException(String.format("entity at index %d was not found for update.", entityIndex));
}
cls = entity.getDtClass();
state = entity.getState();
int nChanged = fieldReader.readFields(stream, cls, state, debug);
evUpdated.raise(entity, fieldReader.getFieldPaths(), nChanged);
if (!entity.isActive()) {
entity.setActive(true);
evEntered.raise(entity);
}
}
} else {
entity = entities[entityIndex];
if (entity == null) {
log.warn("entity at index {} was not found when ordered to leave.", entityIndex);
} else {
if (entity.isActive()) {
entity.setActive(false);
evLeft.raise(entity);
}
if ((cmd & 2) != 0) {
entities[entityIndex] = null;
evDeleted.raise(entity);
}
}
}
}
if (message.getIsDelta()) {
int n = fieldReader.readDeletions(stream, engineType.getIndexBits(), deletions);
for (int i = 0; i < n; i++) {
entityIndex = deletions[i];
entity = entities[entityIndex];
if (entity != null) {
log.debug("entity at index {} was ACTUALLY found when ordered to delete, tell the press!", entityIndex);
if (entity.isActive()) {
entity.setActive(false);
evLeft.raise(entity);
}
evDeleted.raise(entity);
} else {
log.debug("entity at index {} was not found when ordered to delete.", entityIndex);
}
entities[entityIndex] = null;
}
}
evUpdatesCompleted.raise();
}
private Object[] getBaseline(int clsId) {
BaselineEntry be = baselineEntries.get(clsId);
if (be == null) {
throw new RuntimeException(String.format("Baseline for class %s (%d) not found.", dtClasses.forClassId(clsId).getDtName(), clsId));
}
if (be.baseline == null) {
DTClass cls = dtClasses.forClassId(clsId);
BitStream stream = BitStream.createBitStream(be.rawBaseline);
be.baseline = cls.getEmptyStateArray();
fieldReader.readFields(stream, cls, be.baseline, false);
}
return be.baseline;
}
public Entity getByIndex(int index) {
return entities[index];
}
public Entity getByHandle(int handle) {
Entity e = entities[engineType.indexForHandle(handle)];
return e == null || e.getSerial() != engineType.serialForHandle(handle) ? null : e;
}
public Iterator<Entity> getAllByPredicate(final Predicate<Entity> predicate) {
return new SimpleIterator<Entity>() {
int i = -1;
@Override
public Entity readNext() {
while(++i < entities.length) {
Entity e = entities[i];
if (e != null && predicate.apply(e)) {
return e;
}
}
return null;
}
};
}
public Entity getByPredicate(Predicate<Entity> predicate) {
Iterator<Entity> iter = getAllByPredicate(predicate);
return iter.hasNext() ? iter.next() : null;
}
public Iterator<Entity> getAllByDtName(final String dtClassName) {
return getAllByPredicate(
new Predicate<Entity>() {
@Override
public boolean apply(Entity e) {
return dtClassName.equals(e.getDtClass().getDtName());
}
});
}
public Entity getByDtName(final String dtClassName) {
Iterator<Entity> iter = getAllByDtName(dtClassName);
return iter.hasNext() ? iter.next() : null;
}
}
| src/main/java/skadistats/clarity/processor/entities/Entities.java | package skadistats.clarity.processor.entities;
import com.google.protobuf.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import skadistats.clarity.decoder.FieldReader;
import skadistats.clarity.decoder.Util;
import skadistats.clarity.decoder.bitstream.BitStream;
import skadistats.clarity.event.*;
import skadistats.clarity.model.*;
import skadistats.clarity.processor.reader.OnMessage;
import skadistats.clarity.processor.reader.OnReset;
import skadistats.clarity.processor.reader.ResetPhase;
import skadistats.clarity.processor.runner.Context;
import skadistats.clarity.processor.runner.OnInit;
import skadistats.clarity.processor.sendtables.DTClasses;
import skadistats.clarity.processor.sendtables.UsesDTClasses;
import skadistats.clarity.processor.stringtables.OnStringTableEntry;
import skadistats.clarity.util.Predicate;
import skadistats.clarity.util.SimpleIterator;
import skadistats.clarity.wire.common.proto.Demo;
import skadistats.clarity.wire.common.proto.NetMessages;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Provides({ UsesEntities.class, OnEntityCreated.class, OnEntityUpdated.class, OnEntityDeleted.class, OnEntityEntered.class, OnEntityLeft.class, OnEntityUpdatesCompleted.class })
@UsesDTClasses
public class Entities {
private static final Logger log = LoggerFactory.getLogger(Entities.class);
private final Map<Integer, BaselineEntry> baselineEntries = new HashMap<>();
private Entity[] entities;
private int[] deletions;
private FieldReader fieldReader;
@Insert
private EngineType engineType;
@InsertEvent
private Event<OnEntityCreated> evCreated;
@InsertEvent
private Event<OnEntityUpdated> evUpdated;
@InsertEvent
private Event<OnEntityDeleted> evDeleted;
@InsertEvent
private Event<OnEntityEntered> evEntered;
@InsertEvent
private Event<OnEntityLeft> evLeft;
@InsertEvent
private Event<OnEntityUpdatesCompleted> evUpdatesCompleted;
private class BaselineEntry {
private ByteString rawBaseline;
private Object[] baseline;
public BaselineEntry(ByteString rawBaseline) {
this.rawBaseline = rawBaseline;
this.baseline = null;
}
}
@OnInit
public void onInitRun() {
fieldReader = engineType.getNewFieldReader();
entities = new Entity[1 << engineType.getIndexBits()];
deletions = new int[1 << engineType.getIndexBits()];
}
@OnReset
public void onReset(Context ctx, Demo.CDemoStringTables packet, ResetPhase phase) {
if (phase == ResetPhase.CLEAR) {
baselineEntries.clear();
for (int entityIndex = 0; entityIndex < entities.length; entityIndex++) {
entities[entityIndex] = null;
}
}
}
@OnStringTableEntry("instancebaseline")
public void onBaselineEntry(Context ctx, StringTable table, int index, String key, ByteString value) {
baselineEntries.put(Integer.valueOf(key), new BaselineEntry(value));
}
@OnMessage(NetMessages.CSVCMsg_PacketEntities.class)
public void onPacketEntities(Context ctx, NetMessages.CSVCMsg_PacketEntities message) {
BitStream stream = BitStream.createBitStream(message.getEntityData());
DTClasses dtClasses = ctx.getProcessor(DTClasses.class);
int updateCount = message.getUpdatedEntries();
int entityIndex = -1;
int cmd;
int clsId;
DTClass cls;
int serial;
Object[] state;
Entity entity;
boolean debug = false;
if (debug) {
System.out.println(ctx.getBuildNumber());
}
while (updateCount-- != 0) {
entityIndex += stream.readUBitVar() + 1;
cmd = stream.readUBitInt(2);
if ((cmd & 1) == 0) {
if ((cmd & 2) != 0) {
clsId = stream.readUBitInt(dtClasses.getClassBits());
cls = dtClasses.forClassId(clsId);
if (cls == null) {
throw new RuntimeException(String.format("class for new entity %d is %d, but no dtClass found!.", entityIndex, clsId));
}
serial = stream.readUBitInt(engineType.getSerialBits());
if (engineType == EngineType.SOURCE2) {
// TODO: there is an extra VarInt encoded here for S2, figure out what it is
stream.readVarUInt();
}
state = Util.clone(getBaseline(dtClasses, cls.getClassId()));
fieldReader.readFields(stream, cls, state, debug);
entity = new Entity(ctx.getEngineType(), entityIndex, serial, cls, true, state);
entities[entityIndex] = entity;
if (evCreated != null) {
evCreated.raise(entity);
}
if (evEntered != null) {
evEntered.raise(entity);
}
} else {
entity = entities[entityIndex];
if (entity == null) {
throw new RuntimeException(String.format("entity at index %d was not found for update.", entityIndex));
}
cls = entity.getDtClass();
state = entity.getState();
int nChanged = fieldReader.readFields(stream, cls, state, debug);
if (evUpdated != null) {
evUpdated.raise(entity, fieldReader.getFieldPaths(), nChanged);
}
if (!entity.isActive()) {
entity.setActive(true);
if (evEntered != null) {
evEntered.raise(entity);
}
}
}
} else {
entity = entities[entityIndex];
if (entity == null) {
log.warn("entity at index {} was not found when ordered to leave.", entityIndex);
} else {
if (entity.isActive()) {
entity.setActive(false);
if (evLeft != null) {
evLeft.raise(entity);
}
}
if ((cmd & 2) != 0) {
entities[entityIndex] = null;
if (evDeleted != null) {
evDeleted.raise(entity);
}
}
}
}
}
if (message.getIsDelta()) {
int n = fieldReader.readDeletions(stream, engineType.getIndexBits(), deletions);
for (int i = 0; i < n; i++) {
entityIndex = deletions[i];
entity = entities[entityIndex];
if (entity != null) {
log.debug("entity at index {} was ACTUALLY found when ordered to delete, tell the press!", entityIndex);
if (entity.isActive()) {
entity.setActive(false);
if (evLeft != null) {
evLeft.raise(entity);
}
}
if (evDeleted != null) {
evDeleted.raise(entity);
}
} else {
log.debug("entity at index {} was not found when ordered to delete.", entityIndex);
}
entities[entityIndex] = null;
}
}
if (evUpdatesCompleted != null) {
evUpdatesCompleted.raise();
}
}
private Object[] getBaseline(DTClasses dtClasses, int clsId) {
BaselineEntry be = baselineEntries.get(clsId);
if (be == null) {
throw new RuntimeException(String.format("Baseline for class %s (%d) not found.", dtClasses.forClassId(clsId).getDtName(), clsId));
}
if (be.baseline == null) {
DTClass cls = dtClasses.forClassId(clsId);
BitStream stream = BitStream.createBitStream(be.rawBaseline);
be.baseline = cls.getEmptyStateArray();
fieldReader.readFields(stream, cls, be.baseline, false);
}
return be.baseline;
}
public Entity getByIndex(int index) {
return entities[index];
}
public Entity getByHandle(int handle) {
Entity e = entities[engineType.indexForHandle(handle)];
return e == null || e.getSerial() != engineType.serialForHandle(handle) ? null : e;
}
public Iterator<Entity> getAllByPredicate(final Predicate<Entity> predicate) {
return new SimpleIterator<Entity>() {
int i = -1;
@Override
public Entity readNext() {
while(++i < entities.length) {
Entity e = entities[i];
if (e != null && predicate.apply(e)) {
return e;
}
}
return null;
}
};
}
public Entity getByPredicate(Predicate<Entity> predicate) {
Iterator<Entity> iter = getAllByPredicate(predicate);
return iter.hasNext() ? iter.next() : null;
}
public Iterator<Entity> getAllByDtName(final String dtClassName) {
return getAllByPredicate(
new Predicate<Entity>() {
@Override
public boolean apply(Entity e) {
return dtClassName.equals(e.getDtClass().getDtName());
}
});
}
public Entity getByDtName(final String dtClassName) {
Iterator<Entity> iter = getAllByDtName(dtClassName);
return iter.hasNext() ? iter.next() : null;
}
}
| port entities processor to new injection model
| src/main/java/skadistats/clarity/processor/entities/Entities.java | port entities processor to new injection model | <ide><path>rc/main/java/skadistats/clarity/processor/entities/Entities.java
<ide> import skadistats.clarity.decoder.FieldReader;
<ide> import skadistats.clarity.decoder.Util;
<ide> import skadistats.clarity.decoder.bitstream.BitStream;
<del>import skadistats.clarity.event.*;
<del>import skadistats.clarity.model.*;
<add>import skadistats.clarity.event.Event;
<add>import skadistats.clarity.event.Insert;
<add>import skadistats.clarity.event.InsertEvent;
<add>import skadistats.clarity.event.Provides;
<add>import skadistats.clarity.model.DTClass;
<add>import skadistats.clarity.model.EngineType;
<add>import skadistats.clarity.model.Entity;
<add>import skadistats.clarity.model.StringTable;
<ide> import skadistats.clarity.processor.reader.OnMessage;
<ide> import skadistats.clarity.processor.reader.OnReset;
<ide> import skadistats.clarity.processor.reader.ResetPhase;
<del>import skadistats.clarity.processor.runner.Context;
<ide> import skadistats.clarity.processor.runner.OnInit;
<ide> import skadistats.clarity.processor.sendtables.DTClasses;
<ide> import skadistats.clarity.processor.sendtables.UsesDTClasses;
<ide>
<ide> @Insert
<ide> private EngineType engineType;
<add> @Insert
<add> private DTClasses dtClasses;
<ide>
<ide> @InsertEvent
<ide> private Event<OnEntityCreated> evCreated;
<ide> }
<ide>
<ide> @OnReset
<del> public void onReset(Context ctx, Demo.CDemoStringTables packet, ResetPhase phase) {
<add> public void onReset(Demo.CDemoStringTables packet, ResetPhase phase) {
<ide> if (phase == ResetPhase.CLEAR) {
<ide> baselineEntries.clear();
<ide> for (int entityIndex = 0; entityIndex < entities.length; entityIndex++) {
<ide> }
<ide>
<ide> @OnStringTableEntry("instancebaseline")
<del> public void onBaselineEntry(Context ctx, StringTable table, int index, String key, ByteString value) {
<add> public void onBaselineEntry(StringTable table, int index, String key, ByteString value) {
<ide> baselineEntries.put(Integer.valueOf(key), new BaselineEntry(value));
<ide> }
<ide>
<ide> @OnMessage(NetMessages.CSVCMsg_PacketEntities.class)
<del> public void onPacketEntities(Context ctx, NetMessages.CSVCMsg_PacketEntities message) {
<add> public void onPacketEntities(NetMessages.CSVCMsg_PacketEntities message) {
<ide> BitStream stream = BitStream.createBitStream(message.getEntityData());
<del> DTClasses dtClasses = ctx.getProcessor(DTClasses.class);
<ide> int updateCount = message.getUpdatedEntries();
<ide> int entityIndex = -1;
<ide>
<ide> Entity entity;
<ide>
<ide> boolean debug = false;
<del> if (debug) {
<del> System.out.println(ctx.getBuildNumber());
<del> }
<ide>
<ide> while (updateCount-- != 0) {
<ide> entityIndex += stream.readUBitVar() + 1;
<ide> // TODO: there is an extra VarInt encoded here for S2, figure out what it is
<ide> stream.readVarUInt();
<ide> }
<del> state = Util.clone(getBaseline(dtClasses, cls.getClassId()));
<add> state = Util.clone(getBaseline(cls.getClassId()));
<ide> fieldReader.readFields(stream, cls, state, debug);
<del> entity = new Entity(ctx.getEngineType(), entityIndex, serial, cls, true, state);
<add> entity = new Entity(engineType, entityIndex, serial, cls, true, state);
<ide> entities[entityIndex] = entity;
<del> if (evCreated != null) {
<del> evCreated.raise(entity);
<del> }
<del> if (evEntered != null) {
<del> evEntered.raise(entity);
<del> }
<add> evCreated.raise(entity);
<add> evEntered.raise(entity);
<ide> } else {
<ide> entity = entities[entityIndex];
<ide> if (entity == null) {
<ide> cls = entity.getDtClass();
<ide> state = entity.getState();
<ide> int nChanged = fieldReader.readFields(stream, cls, state, debug);
<del> if (evUpdated != null) {
<del> evUpdated.raise(entity, fieldReader.getFieldPaths(), nChanged);
<del> }
<add> evUpdated.raise(entity, fieldReader.getFieldPaths(), nChanged);
<ide> if (!entity.isActive()) {
<ide> entity.setActive(true);
<del> if (evEntered != null) {
<del> evEntered.raise(entity);
<del> }
<add> evEntered.raise(entity);
<ide> }
<ide> }
<ide> } else {
<ide> } else {
<ide> if (entity.isActive()) {
<ide> entity.setActive(false);
<del> if (evLeft != null) {
<del> evLeft.raise(entity);
<del> }
<add> evLeft.raise(entity);
<ide> }
<ide> if ((cmd & 2) != 0) {
<ide> entities[entityIndex] = null;
<del> if (evDeleted != null) {
<del> evDeleted.raise(entity);
<del> }
<add> evDeleted.raise(entity);
<ide> }
<ide> }
<ide> }
<ide> log.debug("entity at index {} was ACTUALLY found when ordered to delete, tell the press!", entityIndex);
<ide> if (entity.isActive()) {
<ide> entity.setActive(false);
<del> if (evLeft != null) {
<del> evLeft.raise(entity);
<del> }
<del> }
<del> if (evDeleted != null) {
<del> evDeleted.raise(entity);
<del> }
<add> evLeft.raise(entity);
<add> }
<add> evDeleted.raise(entity);
<ide> } else {
<ide> log.debug("entity at index {} was not found when ordered to delete.", entityIndex);
<ide> }
<ide> }
<ide> }
<ide>
<del> if (evUpdatesCompleted != null) {
<del> evUpdatesCompleted.raise();
<del> }
<del>
<del> }
<del>
<del> private Object[] getBaseline(DTClasses dtClasses, int clsId) {
<add> evUpdatesCompleted.raise();
<add>
<add> }
<add>
<add> private Object[] getBaseline(int clsId) {
<ide> BaselineEntry be = baselineEntries.get(clsId);
<ide> if (be == null) {
<ide> throw new RuntimeException(String.format("Baseline for class %s (%d) not found.", dtClasses.forClassId(clsId).getDtName(), clsId)); |
|
JavaScript | bsd-3-clause | b16575631ff2ec69c79e92f46c9441f38671e079 | 0 | CBIIT/FHH,CBIIT/FHH,CBIIT/FHH,CBIIT/FHH | var XML_FORMAT_ID = 718163810183;
var TOOL_NAME = "Surgeon General's Family Heath History Tool";
var SNOMED_CODE = {
MALE:248153007, FEMALE:248152002,
HEIGHT:271603002, WEIGHT:107647005,
DEATH:419620001,
IDENTICAL_TWIN:313415001,
FRATERNAL_TWIN:313416000,
ADOPTED:160496001,
PHYSICALLY_ACTIVE:228447005
};
var LOINC_CODE = {
ESTIMATED_AGE:"21611-9",
AGE_AT_DEATH:"39016-1"
};
var XMLNS_SCHEMA= "http://www.w3.org/2001/XMLSchema-instance";
// Important for generating the xml
var doc;
var filename;
var output_string;
function bind_save_xml() {
doc = document.implementation.createDocument("urn:hl7-org:v3", "FamilyHistory", null);
bind_save_download();
bind_save_dropbox ();
bind_save_google_drive ();
bind_save_heath_vault();
}
function get_filename(pi) {
var filename = "family_health_history.xml";
if (pi && pi.name) {
filename = pi.name.replace(/ /g,"_") + "_Health_History.xml";
}
return filename;
}
function get_xml_string() {
var root = doc.createElement("FamilyHistory");
add_root_information(root);
root.appendChild(add_personal_history(personal_information));
var s = new XMLSerializer();
return(s.serializeToString(root));
}
function bind_save_download() {
$("#download_xml").on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
save_document($(this), output_string, filename);
$("#save_personal_history_dialog").dialog("close");
});
}
function bind_save_dropbox () {
if (typeof DROPBOX_APP_KEY == 'undefined') {
if (typeof DEBUG != 'undefined' && DEBUG) $("#save_to_dropbox").append("No Dropbox App Key Defined");
else $("#save_to_dropbox").append("Coming Soon");
return;
}
var button = $("<BUTTON id='dropbox_save_button'>" + $.t("fhh_load_save.save_dropbox_button") + "</BUTTON>");
button.on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
Dropbox.save({
files: [ {'url': 'data:application/xml,' + output_string, 'filename': filename } ],
success: function () { $("#save_personal_history_dialog").dialog("close");},
error: function (errorMessage) { alert ("ERROR:" + errorMessage);}
});
});
$("#save_to_dropbox").append(button);
}
function bind_save_google_drive () {
if (typeof GOOGLE_CLIENT_ID == 'undefined') {
if (typeof DEBUG != 'undefined' && DEBUG) $("#save_to_google_drive").append("No Google Drive App Key Defined");
else $("#save_to_google_drive").append("Coming Soon");
return;
}
var button = $("<BUTTON id='google_drive_save_button'>" + $.t("fhh_load_save.save_google_drive_button") + "</BUTTON>");
button.on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
// this is an aysncronous call, we need to improve the user experience here somehow.
gapi.auth.authorize( {'client_id': GOOGLE_CLIENT_ID, 'scope': GOOGLE_SCOPES, 'immediate': false}, googlePostAuthSave);
});
$("#save_to_google_drive").append(button);
}
function googlePostAuthSave(authResult) {
// output_string is a global
if (authResult && !authResult.error) {
/// See google examples for how this works
var request = gapi.client.request({
'path': 'drive/v2/files',
'method': 'GET'
});
var cb2 = function(data) {
var items = data.items;
var file_id = "";
var request_type = 'POST';
if (items.length > 0) {
file_id = items[0].id;
request_type = 'PUT'
}
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var content_type ='text/plain';
var string_data = $("#input").val();
var metadata = {
'title': filename,
'mimeType': content_type
};
var base64Data = btoa(output_string);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + content_type + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + file_id,
'method': request_type,
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody
});
var callback = function(file) {
$("#save_personal_history_dialog").dialog("close");
};
request.execute(callback);
};
request.execute(cb2);
}
}
function bind_save_heath_vault() {
}
function add_root_information(root) {
root.setAttribute("moodCode", "EVN");
root.setAttribute("classCode", "OBS");
id_tag = doc.createElement("id");
id_tag.setAttribute("extention", "gov.hhs.fhh:" + XML_FORMAT_ID);
root.appendChild(id_tag);
effectiveTime_tag = doc.createElement("effectiveTime");
date = new Date();
effectiveTime_tag.setAttribute("value", date.toLocaleDateString());
root.appendChild(effectiveTime_tag);
methodCode_tag = doc.createElement("methodCode");
methodCode_tag.setAttribute("displayName", TOOL_NAME);
root.appendChild(methodCode_tag);
}
function add_personal_history(pi) {
subject_tag = doc.createElement("subject");
subject_tag.setAttribute("typeCode", "SBJ");
patient_tag = doc.createElement("patient");
patient_tag.setAttribute("classCode", "PAT");
subject_tag.appendChild(patient_tag);
patientPerson_tag = doc.createElement("patientPerson");
patient_tag.appendChild(patientPerson_tag);
add_personal_information (patientPerson_tag, pi);
return subject_tag;
}
function add_personal_information(patient_tag, pi) {
if (personal_information == null) return;
add_id(patient_tag, pi.id);
add_name(patient_tag, pi.name);
add_birthday(patient_tag, pi.date_of_birth);
add_gender(patient_tag, pi.gender);
add_all_ethnic_groups(patient_tag, pi.ethnicity);
add_all_races(patient_tag, pi.race);
add_clinical_observations(patient_tag,
pi.height,
pi.height_unit,
pi.weight,
pi.weight_unit,
pi.consanguinity,
pi["Health History"],
null,
pi.twin_status,
pi.adopted,
pi.physically_active
);
add_relatives(patient_tag, pi);
}
function add_id(tag, id_text) {
if (id_text == null) return;
id_tag = doc.createElement("id");
id_tag.setAttribute("extension", id_text);
tag.appendChild(id_tag);
}
function add_name(tag, personal_name) {
if (personal_name == null || personal_name=='undefined') personal_name="";
name_tag = doc.createElement("name");
name_tag.setAttribute("formatted", personal_name);
tag.appendChild(name_tag);
}
function add_birthday(tag, birthday) {
if (birthday == null) return;
birthday_tag = doc.createElement("birthTime");
birthday_tag.setAttribute("value", birthday);
tag.appendChild(birthday_tag);
}
function add_parent(tag, parent_id) {
var relative_tag = doc.createElement("relative");
tag.appendChild(relative_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Parent");
code_tag.setAttribute("codeSystemName", "HL7 Family History Model");
code_tag.setAttribute("code", "PAR");
relative_tag.appendChild(code_tag);
var relationshipHolder_tag = doc.createElement("relationshipHolder");
relative_tag.appendChild(relationshipHolder_tag);
if (parent_id != null) {
var id_tag = doc.createElement("id");
id_tag.setAttribute("extension", "" + parent_id);
relationshipHolder_tag.appendChild(id_tag);
}
}
function add_gender(tag, gender) {
gender_tag = doc.createElement("administrativeGenderCode");
gender_tag.setAttribute("codeSystemName", "SNOMED_CT");
if (gender == "MALE") {
gender_tag.setAttribute("displayName", "male");
gender_tag.setAttribute("code", SNOMED_CODE.MALE);
} else if (gender == "FEMALE") {
gender_tag.setAttribute("displayName", "female");
gender_tag.setAttribute("code", SNOMED_CODE.FEMALE);
}
tag.appendChild(gender_tag);
}
function add_consanguinity(tag, consanguinity) {
if (consanguinity) {
var consanguinity_tag = doc.createElement("clinicalObservation");
tag.appendChild(consanguinity_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("originalText", "Parental consanguinity indicated");
consanguinity_tag.appendChild(code_tag);
}
}
function add_all_ethnic_groups(tag, ethnic_group_list) {
if (ethnic_group_list == null) return
if (ethnic_group_list["Hispanic or Latino"] == true) add_individual_ethnic_group(tag, "Hispanic or Latino");
if (ethnic_group_list["Ashkenazi Jewish"] == true) add_individual_ethnic_group(tag, "Ashkenazi Jewish");
if (ethnic_group_list["Not Hispanic or Latino"] == true) add_individual_ethnic_group(tag, "Not Hispanic or Latino");
if (ethnic_group_list["Central American"] == true) add_individual_ethnic_group(tag, "Central American");
if (ethnic_group_list["Cuban"] == true) add_individual_ethnic_group(tag, "Cuban");
if (ethnic_group_list["Dominican"] == true) add_individual_ethnic_group(tag, "Dominican");
if (ethnic_group_list["Mexican"] == true) add_individual_ethnic_group(tag, "Mexican");
if (ethnic_group_list["Other Hispanic"] == true) add_individual_ethnic_group(tag, "Other Hispanic");
if (ethnic_group_list["Puerto Rican"] == true) add_individual_ethnic_group(tag, "Puerto Rican");
if (ethnic_group_list["South American"] == true) add_individual_ethnic_group(tag, "South American");
}
function add_individual_ethnic_group(tag, ethnic_group) {
ethnic_group_tag = doc.createElement("ethnicGroupCode");
ethnic_group_tag.setAttribute("displayName", ethnic_group);
cv = get_code_for_ethnicity(ethnic_group);
ethnic_group_tag.setAttribute("code", cv.code );
ethnic_group_tag.setAttribute("codeSystemName", cv.code_system);
if (cv.id) ethnic_group_tag.setAttribute("id", cv.id);
if (cv.xsi_type) ethnic_group_tag.setAttribute("xsi:type", cv.xsi_type);
if (cv.ns) ethnic_group_tag.setAttribute("xmlns:xsi", cv.ns);
tag.appendChild(ethnic_group_tag);
}
function add_all_races(tag, race_list) {
if (race_list == null) return
if (race_list["American Indian or Alaska Native"] == true) add_individual_race(tag, "American Indian or Alaska Native");
if (race_list["Asian"] == true) add_individual_race(tag, "Asian");
if (race_list["Black or African-American"] == true) add_individual_race(tag, "Black or African-American");
if (race_list["Native Hawaiian or Other Pacific Islander"] == true) add_individual_race(tag, "Native Hawaiian or Other Pacific Islander");
if (race_list["White"] == true) add_individual_race(tag, "White");
if (race_list["Asian Indian"] == true) add_individual_race(tag, "Asian Indian");
if (race_list["Chinese"] == true) add_individual_race(tag, "Chinese");
if (race_list["Filipino"] == true) add_individual_race(tag, "Filipino");
if (race_list["Japanese"] == true) add_individual_race(tag, "Japanese");
if (race_list["Korean"] == true) add_individual_race(tag, "Korean");
if (race_list["Vietnamese"] == true) add_individual_race(tag, "Vietnamese");
if (race_list["Other Asian"] == true) add_individual_race(tag, "Other Asian");
if (race_list["Unknown Asian"] == true) add_individual_race(tag, "Unknown Asian");
if (race_list["Chamorro"] == true) add_individual_race(tag, "Chamorro");
if (race_list["Guamanian"] == true) add_individual_race(tag, "Guamanian");
if (race_list["Native Hawaiian"] == true) add_individual_race(tag, "Native Hawaiian");
if (race_list["Samoan"] == true) add_individual_race(tag, "Samoan");
if (race_list["Unknown South Pacific Islander"] == true) add_individual_race(tag, "Unknown South Pacific Islander");
}
function add_individual_race(tag, race) {
race_tag = doc.createElement("raceCode");
race_tag.setAttribute("displayName", race);
cv = get_code_for_race(race);
race_tag.setAttribute("code", cv.code );
race_tag.setAttribute("codeSystemName", cv.code_system);
if (cv.id) race_tag.setAttribute("id", cv.id);
if (cv.xsi_type) race_tag.setAttribute("xsi:type", cv.xsi_type);
if (cv.ns) race_tag.setAttribute("xmlns:xsi", cv.ns);
tag.appendChild(race_tag);
}
function add_clinical_observations(tag,
height, height_unit,
weight, weight_unit,
consanguinity,
diseases,
cause_of_death,
twin_status,
adopted_flag,
active_flag)
{
var subjectOfTwo_tag = doc.createElement("subjectof2");
tag.appendChild(subjectOfTwo_tag);
add_twin_tag(subjectOfTwo_tag, twin_status);
add_adopted_tag(subjectOfTwo_tag, adopted_flag);
add_active_tag(subjectOfTwo_tag, active_flag);
add_height(subjectOfTwo_tag, height, height_unit);
add_weight(subjectOfTwo_tag, weight, weight_unit);
add_consanguinity(subjectOfTwo_tag, consanguinity);
add_diseases(subjectOfTwo_tag, diseases);
add_cause_of_death(subjectOfTwo_tag, cause_of_death);
}
function add_twin_tag(tag, twin_status) {
if (twin_status == null || twin_status == "") return;
if (!(twin_status == "IDENTICAL" || twin_status == "FRATERNAL")) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
if (twin_status == "IDENTICAL") {
code_tag.setAttribute("displayName", "Identical twin (person)");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.IDENTICAL_TWIN);
} else if (twin_status == "FRATERNAL") {
code_tag.setAttribute("displayName", "Fraternal twin (person)");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.FRATERNAL_TWIN);
}
observation_tag.appendChild(code_tag);
}
function add_adopted_tag(tag, adopted_tag) {
if (adopted_tag == null || !(adopted_tag == "true" || adopted_tag == true)) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "adopted");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.ADOPTED);
observation_tag.appendChild(code_tag);
}
function add_active_tag(tag, active_tag) {
if (active_tag == null) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Physically Active");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.PHYSICALLY_ACTIVE);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", active_tag);
observation_tag.appendChild(value_tag);
}
function add_height(tag, height, height_unit) {
if (height == null || height == "") return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "height");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.HEIGHT);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", height);
value_tag.setAttribute("unit", height_unit);
observation_tag.appendChild(value_tag);
}
function add_weight(tag, weight, weight_unit) {
if (weight == null || weight == "") return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "weight");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.WEIGHT);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", weight);
value_tag.setAttribute("unit", weight_unit);
observation_tag.appendChild(value_tag);
}
function add_diseases(tag, diseases) {
if (diseases == null) return;
for (var i=0; i<diseases.length;i++) {
var disease_name = diseases[i]["Disease Name"];
var detailed_disease_name = diseases[i]["Detailed Disease Name"];
var disease_code_and_system = diseases[i]["Disease Code"];
if (!detailed_disease_name) detailed_disease_name = disease_name;
var age_at_diagnosis = diseases[i]["Age At Diagnosis"];
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
if (disease_code_and_system) {
var dcas = disease_code_and_system.split("-");
var disease_code_system = dcas[0];
var disease_code = dcas[1];
code_tag.setAttribute("codeSystemName", disease_code_system);
code_tag.setAttribute("code", disease_code);
var potential_detailed_disease_name = get_detailed_disease_name_from_code(disease_code);
if (potential_detailed_disease_name != null) detailed_disease_name = potential_detailed_disease_name;
// alert (potential_detailed_disease_name + "->" + detailed_disease_name);
}
code_tag.setAttribute("displayName", detailed_disease_name);
code_tag.setAttribute("originalText", detailed_disease_name);
// code_tag.setAttribute("codeSystemName", "SNOMED COMPLETE"); //
observation_tag.appendChild(code_tag);
var subject_tag = doc.createElement("subject");
observation_tag.appendChild(subject_tag);
var dataEstimatedAge_tag = doc.createElement("dataEstimatedAge");
subject_tag.appendChild(dataEstimatedAge_tag);
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("displayName", "Estimated Age");
new_code_tag.setAttribute("codeSystemName", "LOINC");
new_code_tag.setAttribute("code", LOINC_CODE.ESTIMATED_AGE);
dataEstimatedAge_tag.appendChild(new_code_tag);
add_estimated_age_tag(dataEstimatedAge_tag, age_at_diagnosis);
}
}
function add_estimated_age_tag(tag, estimated_age) {
var av = get_age_values_from_estimated_age(estimated_age);
if (estimated_age == "Pre-Birth") {
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("originalText", "pre-birth");
tag.appendChild(new_code_tag);
} else if (estimated_age == "Unknown") {
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("originalText", "unknown");
tag.appendChild(new_code_tag);
} else {
// These estimates ages have high, low, and unit tags/attr
var new_value_tag = doc.createElement("value");
tag.appendChild(new_value_tag);
if (av && av.unit) {
new_value_tag.setAttribute("unit", av.unit);
}
if (av && av.low) {
var low_tag = doc.createElement("low");
low_tag.setAttribute("value", av.low);
new_value_tag.appendChild(low_tag);
}
if (av && av.high) {
var high_tag = doc.createElement("high");
high_tag.setAttribute("value", av.high);
new_value_tag.appendChild(high_tag);
}
}
}
function add_death_status (tag, cause_of_death) {
if (cause_of_death == null) return;
var deceasedIndCode_tag = doc.createElement("deceasedIndCode");
deceasedIndCode_tag.setAttribute("value", "true");
tag.appendChild(deceasedIndCode_tag);
}
function add_death_age(tag, estimated_death_age) {
if (estimated_death_age == null) return;
var subjectOfOne_tag = doc.createElement("subjectOf1");
tag.appendChild(subjectOfOne_tag);
var deceasedEstimatedAge_tag = doc.createElement("deceasedEstimatedAge");
subjectOfOne_tag.appendChild(deceasedEstimatedAge_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Age at Death");
code_tag.setAttribute("codeSystemName", "LOINC");
code_tag.setAttribute("code", LOINC_CODE.AGE_AT_DEATH);
deceasedEstimatedAge_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
add_estimated_age_tag(deceasedEstimatedAge_tag, estimated_death_age);
}
function add_cause_of_death(tag, cause_of_death) {
if (cause_of_death == null) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", cause_of_death);
code_tag.setAttribute("originalText", cause_of_death);
code_tag.setAttribute("codeSystemName", "SNOMED COMPLETE");
observation_tag.appendChild(code_tag);
var sourceOf_tag = doc.createElement("sourceOf");
observation_tag.appendChild(sourceOf_tag);
var newcode_tag = doc.createElement("code");
newcode_tag.setAttribute("displayName", "death");
newcode_tag.setAttribute("codeSystemName", "SNOMED_CT");
newcode_tag.setAttribute("code", SNOMED_CODE.DEATH);
sourceOf_tag.appendChild(newcode_tag);
}
function add_relatives(tag, pi) {
if (pi.mother) add_individual_relative(tag, "Mother", "NMTH", pi.mother);
if (pi.father) add_individual_relative(tag, "Father", "NFTH", pi.father);
if (pi.maternal_grandmother) add_individual_relative(tag, "Maternal Grandmother", "MGRMTH", pi.maternal_grandmother);
if (pi.maternal_grandfather) add_individual_relative(tag, "Maternal Grandfather", "MGRFTH", pi.maternal_grandfather);
if (pi.paternal_grandmother) add_individual_relative(tag, "Paternal Grandmother", "PGRMTH", pi.paternal_grandmother);
if (pi.paternal_grandfather) add_individual_relative(tag, "Paternal Grandfather", "PGRFTH", pi.paternal_grandfather);
var i = 0;
while (pi['brother_' + i] != null) {
add_individual_relative(tag, "Brother", "NBRO", pi['brother_' + i]);
i++;
}
var i = 0;
while (pi['sister_' + i] != null) {
add_individual_relative(tag, "Sister", "NSIS", pi['sister_' + i]);
i++;
}
var i = 0;
while (pi['son_' + i] != null) {
add_individual_relative(tag, "Son", "SON", pi['son_' + i]);
i++;
}
var i = 0;
while (pi['daughter_' + i] != null) {
add_individual_relative(tag, "Daughter", "DAU", pi['daughter_' + i]);
i++;
}
var i = 0;
while (pi['maternal_aunt_' + i] != null) {
add_individual_relative(tag, "Maternal Aunt", "MAUNT", pi['maternal_aunt_' + i]);
i++;
}
var i = 0;
while (pi['maternal_uncle_' + i] != null) {
add_individual_relative(tag, "Maternal Uncle", "MUNCLE", pi['maternal_uncle_' + i]);
i++;
}
var i = 0;
while (pi['paternal_aunt_' + i] != null) {
add_individual_relative(tag, "Paternal Aunt", "PAUNT", pi['paternal_aunt_' + i]);
i++;
}
var i = 0;
while (pi['paternal_uncle_' + i] != null) {
add_individual_relative(tag, "Paternal Uncle", "PUNCLE", pi['paternal_uncle_' + i]);
i++;
}
var i = 0;
while (pi['maternal_cousin_' + i] != null) {
add_individual_relative(tag, "Maternal Cousin", "MCOUSN", pi['maternal_cousin_' + i]);
i++;
}
var i = 0;
while (pi['paternal_cousin_' + i] != null) {
add_individual_relative(tag, "Paternal Cousin", "PCOUSN", pi['paternal_cousin_' + i]);
i++;
}
var i = 0;
while (pi['niece_' + i] != null) {
add_individual_relative(tag, "Niece", "NIECE", pi['niece_' + i]);
i++;
}
var i = 0;
while (pi['nephew_' + i] != null) {
add_individual_relative(tag, "Nephew", "NEPHEW", pi['nephew_' + i]);
i++;
}
var i = 0;
while (pi['grandson_' + i] != null) {
add_individual_relative(tag, "Grandson", "GRDSON", pi['grandson_' + i]);
i++;
}
var i = 0;
while (pi['granddaughter_' + i] != null) {
add_individual_relative(tag, "GrandDaughter", "GRDDAU", pi['granddaughter_' + i]);
i++;
}
var i = 0;
while (pi['maternal_halfbrother_' + i] != null) {
add_individual_relative(tag, "Maternal Halfbrother", "MHBRO", pi['maternal_halfbrother_' + i]);
i++;
}
var i = 0;
while (pi['maternal_halfsister_' + i] != null) {
add_individual_relative(tag, "Maternal Halfsister", "MHSIS", pi['maternal_halfsister_' + i]);
i++;
}
var i = 0;
while (pi['paternal_halfbrother_' + i] != null) {
add_individual_relative(tag, "Paternal Halfbrother", "PHBRO", pi['paternal_halfbrother_' + i]);
i++;
}
var i = 0;
while (pi['paternal_halfsister_' + i] != null) {
add_individual_relative(tag, "Paternal Halfsister", "PHSIS", pi['paternal_halfsister_' + i]);
i++;
}
}
function add_individual_relative(tag, relative_type, code, relative) {
var relative_tag = doc.createElement("relative");
tag.appendChild(relative_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", relative_type);
code_tag.setAttribute("codeSystemName", "HL7 Family History Model");
code_tag.setAttribute("code", code);
relative_tag.appendChild(code_tag);
var relationshipHolder_tag = doc.createElement("relationshipHolder");
relative_tag.appendChild(relationshipHolder_tag);
add_parent(relationshipHolder_tag, relative.parent_id);
add_gender(relationshipHolder_tag, relative.gender);
add_all_ethnic_groups(relationshipHolder_tag, relative.ethnicity);
add_all_races(relationshipHolder_tag, relative.race);
add_death_age(relationshipHolder_tag, relative.estimated_death_age);
add_clinical_observations(relationshipHolder_tag,
null, null,
null, null,
null,
relative["Health History"],
relative.detailed_cause_of_death,
relative.twin_status,
relative.adopted,
null
);
add_id(relationshipHolder_tag, relative.id);
add_name(relationshipHolder_tag, relative.name);
add_birthday(relationshipHolder_tag, relative.date_of_birth);
add_death_status(relationshipHolder_tag, relative.cause_of_death);
}
// Functions to convert between code systems and display names
function get_code_for_ethnicity(str) {
switch (str) {
case "Hispanic or Latino": return {code:"2135-2", code_system:"HL7-TBD", id:"1"};
case "Ashkenazi Jewish": return {code:"81706006", code_system:"SNOMED_CT", id:"2"};
case "Not Hispanic or Latino": return {code:"2186-5", code_system:"HL7-TBD", id:"3"};
case "Central American": return {code:"2155-0", code_system:"HL7", id:"4", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Cuban": return {code:"2182-4", code_system:"HL7", id:"5", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Dominican": return {code:"2184-0", code_system:"HL7", id:"6", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Mexican": return {code:"2148-5", code_system:"HL7", id:"7", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Other Hispanic": return {code:"1000000", code_system:"TBD", id:"8", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Puerto Rican": return {code:"2180-8", code_system:"HL7", id:"9", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "South American": return {code:"2165-9", code_system:"HL7", id:"10", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
}
return null;
}
function get_code_for_race(str) {
switch (str) {
case "American Indian or Alaska Native": return {code:"1002-5", code_system:"HL7", id:"1"};
case "Asian": return {code:"1000000", code_system:"TBD", id:"2"};
case "Black or African-American": return {code:"2054-5", code_system:"HL7", id:"3"};
case "Native Hawaiian or Other Pacific Islander": return {code:"1000001", code_system:"TBD", id:"4"};
case "White": return {code:"2106-3", code_system:"HL7", id:"5"};
case "Asian Indian": return {code:"2029-7", code_system:"HL7", id:"11"};
case "Chinese": return {code:"2034-7", code_system:"HL7", id:"12"};
case "Filipino": return {code:"2036-2", code_system:"HL7", id:"13"};
case "Japanese": return {code:"2039-6", code_system:"HL7", id:"14"};
case "Korean": return {code:"2040-4", code_system:"HL7", id:"15"};
case "Vietnamese": return {code:"2047-9", code_system:"HL7", id:"16"};
case "Other Asian": return {code:"186046006", code_system:"SNOMED", id:"17"};
case "Unknown Asian": return {code:"2028-9", code_system:"HL7", id:"18"};
case "Chamorro": return {code:"2088-3", code_system:"HL7", id:"21"};
case "Guamanian": return {code:"2087-5", code_system:"HL7", id:"22"};
case "Native Hawaiian": return {code:"2079-2", code_system:"HL7", id:"23"};
case "Samoan": return {code:"2080-0", code_system:"HL7", id:"24"};
case "Unknown South Pacific Islander": return {code:"2076-8", code_system:"HL7", id:"25"};
}
return null;
}
function get_age_values_from_estimated_age(age_at_diagnosis) {
switch (age_at_diagnosis) {
case "prebirth": return null;
case "newborn": return {unit:"day", low:"0", high:"28"};
case "infant": return {unit:"day", low:"29", high:"729"};
case "child": return {unit:"year", low:"2", high:"10"};
case "teen": return {unit:"year", low:"11", high:"19"};
case "twenties": return {unit:"year", low:"20", high:"29"};
case "thirties": return {unit:"year", low:"30", high:"39"};
case "fourties": return {unit:"year", low:"40", high:"49"};
case "fifties": return {unit:"year", low:"50", high:"59"};
case "senior": return {unit:"year", low:"60", high:null};
case "unknown": return null;
}
return null;
}
function save_document(save_link, output_string, filename) {
if (isIE10) {
var blobObject = new Blob([output_string]);
window.navigator.msSaveBlob(blobObject, filename); // The user only has the option of clicking the Save button.
} else {
save_link.attr("href", "data:application/xml," + output_string ).attr("download", filename);
}
}
// function get_detailed_disease_name_from_code(disease_code) moved to load_xml.js
//// Helper to detect IE10
var isIE10 = false;
/*@cc_on
if (/^10/.test(@_jscript_version)) {
isIE10 = true;
}
@*/
| js/save_xml.js | var XML_FORMAT_ID = 718163810183;
var TOOL_NAME = "Surgeon General's Family Heath History Tool";
var SNOMED_CODE = {
MALE:248153007, FEMALE:248152002,
HEIGHT:271603002, WEIGHT:107647005,
DEATH:419620001,
IDENTICAL_TWIN:313415001,
FRATERNAL_TWIN:313416000,
ADOPTED:160496001,
PHYSICALLY_ACTIVE:228447005
};
var LOINC_CODE = {
ESTIMATED_AGE:"21611-9",
AGE_AT_DEATH:"39016-1"
};
var XMLNS_SCHEMA= "http://www.w3.org/2001/XMLSchema-instance";
// Important for generating the xml
var doc;
var filename;
var output_string;
function bind_save_xml() {
doc = document.implementation.createDocument("urn:hl7-org:v3", "FamilyHistory", null);
bind_save_download();
bind_save_dropbox ();
bind_save_google_drive ();
bind_save_heath_vault();
}
function get_filename(pi) {
var filename = "family_health_history.xml";
if (pi && pi.name) {
filename = pi.name.replace(/ /g,"_") + "_Health_History.xml";
}
return filename;
}
function get_xml_string() {
var root = doc.createElement("FamilyHistory");
add_root_information(root);
root.appendChild(add_personal_history(personal_information));
var s = new XMLSerializer();
return(s.serializeToString(root));
}
function bind_save_download() {
$("#download_xml").on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
save_document($(this), output_string, filename);
$("#save_personal_history_dialog").dialog("close");
});
}
function bind_save_dropbox () {
if (typeof DROPBOX_APP_KEY == 'undefined') {
if (typeof DEBUG != 'undefined' && DEBUG) $("#save_to_dropbox").append("No Dropbox App Key Defined");
else $("#save_to_dropbox").append("Coming Soon");
return;
}
var button = $("<BUTTON id='dropbox_save_button'>" + $.t("fhh_load_save.save_dropbox_button") + "</BUTTON>");
button.on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
Dropbox.save({
files: [ {'url': 'data:application/xml,' + output_string, 'filename': filename } ],
success: function () { $("#save_personal_history_dialog").dialog("close");},
error: function (errorMessage) { alert ("ERROR:" + errorMessage);}
});
});
$("#save_to_dropbox").append(button);
}
function bind_save_google_drive () {
if (typeof GOOGLE_CLIENT_ID == 'undefined') {
if (typeof DEBUG != 'undefined' && DEBUG) $("#save_to_google_drive").append("No Google Drive App Key Defined");
else $("#save_to_google_drive").append("Coming Soon");
return;
}
var button = $("<BUTTON id='google_drive_save_button'>" + $.t("fhh_load_save.save_google_drive_button") + "</BUTTON>");
button.on("click", function () {
output_string = get_xml_string();
filename = get_filename(personal_information);
// this is an aysncronous call, we need to improve the user experience here somehow.
gapi.auth.authorize( {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false}, googlePostAuthSave);
});
$("#save_to_google_drive").append(button);
}
function googlePostAuthSave(authResult) {
// output_string is a global
if (authResult && !authResult.error) {
/// See google examples for how this works
var request = gapi.client.request({
'path': 'drive/v2/files',
'method': 'GET'
});
var cb2 = function(data) {
var items = data.items;
var file_id = "";
var request_type = 'POST';
if (items.length > 0) {
file_id = items[0].id;
request_type = 'PUT'
}
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var content_type ='text/plain';
var string_data = $("#input").val();
var metadata = {
'title': filename,
'mimeType': content_type
};
var base64Data = btoa(output_string);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + content_type + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + file_id,
'method': request_type,
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody
});
var callback = function(file) {
$("#save_personal_history_dialog").dialog("close");
};
request.execute(callback);
};
request.execute(cb2);
}
}
function bind_save_heath_vault() {
}
function add_root_information(root) {
root.setAttribute("moodCode", "EVN");
root.setAttribute("classCode", "OBS");
id_tag = doc.createElement("id");
id_tag.setAttribute("extention", "gov.hhs.fhh:" + XML_FORMAT_ID);
root.appendChild(id_tag);
effectiveTime_tag = doc.createElement("effectiveTime");
date = new Date();
effectiveTime_tag.setAttribute("value", date.toLocaleDateString());
root.appendChild(effectiveTime_tag);
methodCode_tag = doc.createElement("methodCode");
methodCode_tag.setAttribute("displayName", TOOL_NAME);
root.appendChild(methodCode_tag);
}
function add_personal_history(pi) {
subject_tag = doc.createElement("subject");
subject_tag.setAttribute("typeCode", "SBJ");
patient_tag = doc.createElement("patient");
patient_tag.setAttribute("classCode", "PAT");
subject_tag.appendChild(patient_tag);
patientPerson_tag = doc.createElement("patientPerson");
patient_tag.appendChild(patientPerson_tag);
add_personal_information (patientPerson_tag, pi);
return subject_tag;
}
function add_personal_information(patient_tag, pi) {
if (personal_information == null) return;
add_id(patient_tag, pi.id);
add_name(patient_tag, pi.name);
add_birthday(patient_tag, pi.date_of_birth);
add_gender(patient_tag, pi.gender);
add_all_ethnic_groups(patient_tag, pi.ethnicity);
add_all_races(patient_tag, pi.race);
add_clinical_observations(patient_tag,
pi.height,
pi.height_unit,
pi.weight,
pi.weight_unit,
pi.consanguinity,
pi["Health History"],
null,
pi.twin_status,
pi.adopted,
pi.physically_active
);
add_relatives(patient_tag, pi);
}
function add_id(tag, id_text) {
if (id_text == null) return;
id_tag = doc.createElement("id");
id_tag.setAttribute("extension", id_text);
tag.appendChild(id_tag);
}
function add_name(tag, personal_name) {
if (personal_name == null || personal_name=='undefined') personal_name="";
name_tag = doc.createElement("name");
name_tag.setAttribute("formatted", personal_name);
tag.appendChild(name_tag);
}
function add_birthday(tag, birthday) {
if (birthday == null) return;
birthday_tag = doc.createElement("birthTime");
birthday_tag.setAttribute("value", birthday);
tag.appendChild(birthday_tag);
}
function add_parent(tag, parent_id) {
var relative_tag = doc.createElement("relative");
tag.appendChild(relative_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Parent");
code_tag.setAttribute("codeSystemName", "HL7 Family History Model");
code_tag.setAttribute("code", "PAR");
relative_tag.appendChild(code_tag);
var relationshipHolder_tag = doc.createElement("relationshipHolder");
relative_tag.appendChild(relationshipHolder_tag);
if (parent_id != null) {
var id_tag = doc.createElement("id");
id_tag.setAttribute("extension", "" + parent_id);
relationshipHolder_tag.appendChild(id_tag);
}
}
function add_gender(tag, gender) {
gender_tag = doc.createElement("administrativeGenderCode");
gender_tag.setAttribute("codeSystemName", "SNOMED_CT");
if (gender == "MALE") {
gender_tag.setAttribute("displayName", "male");
gender_tag.setAttribute("code", SNOMED_CODE.MALE);
} else if (gender == "FEMALE") {
gender_tag.setAttribute("displayName", "female");
gender_tag.setAttribute("code", SNOMED_CODE.FEMALE);
}
tag.appendChild(gender_tag);
}
function add_consanguinity(tag, consanguinity) {
if (consanguinity) {
var consanguinity_tag = doc.createElement("clinicalObservation");
tag.appendChild(consanguinity_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("originalText", "Parental consanguinity indicated");
consanguinity_tag.appendChild(code_tag);
}
}
function add_all_ethnic_groups(tag, ethnic_group_list) {
if (ethnic_group_list == null) return
if (ethnic_group_list["Hispanic or Latino"] == true) add_individual_ethnic_group(tag, "Hispanic or Latino");
if (ethnic_group_list["Ashkenazi Jewish"] == true) add_individual_ethnic_group(tag, "Ashkenazi Jewish");
if (ethnic_group_list["Not Hispanic or Latino"] == true) add_individual_ethnic_group(tag, "Not Hispanic or Latino");
if (ethnic_group_list["Central American"] == true) add_individual_ethnic_group(tag, "Central American");
if (ethnic_group_list["Cuban"] == true) add_individual_ethnic_group(tag, "Cuban");
if (ethnic_group_list["Dominican"] == true) add_individual_ethnic_group(tag, "Dominican");
if (ethnic_group_list["Mexican"] == true) add_individual_ethnic_group(tag, "Mexican");
if (ethnic_group_list["Other Hispanic"] == true) add_individual_ethnic_group(tag, "Other Hispanic");
if (ethnic_group_list["Puerto Rican"] == true) add_individual_ethnic_group(tag, "Puerto Rican");
if (ethnic_group_list["South American"] == true) add_individual_ethnic_group(tag, "South American");
}
function add_individual_ethnic_group(tag, ethnic_group) {
ethnic_group_tag = doc.createElement("ethnicGroupCode");
ethnic_group_tag.setAttribute("displayName", ethnic_group);
cv = get_code_for_ethnicity(ethnic_group);
ethnic_group_tag.setAttribute("code", cv.code );
ethnic_group_tag.setAttribute("codeSystemName", cv.code_system);
if (cv.id) ethnic_group_tag.setAttribute("id", cv.id);
if (cv.xsi_type) ethnic_group_tag.setAttribute("xsi:type", cv.xsi_type);
if (cv.ns) ethnic_group_tag.setAttribute("xmlns:xsi", cv.ns);
tag.appendChild(ethnic_group_tag);
}
function add_all_races(tag, race_list) {
if (race_list == null) return
if (race_list["American Indian or Alaska Native"] == true) add_individual_race(tag, "American Indian or Alaska Native");
if (race_list["Asian"] == true) add_individual_race(tag, "Asian");
if (race_list["Black or African-American"] == true) add_individual_race(tag, "Black or African-American");
if (race_list["Native Hawaiian or Other Pacific Islander"] == true) add_individual_race(tag, "Native Hawaiian or Other Pacific Islander");
if (race_list["White"] == true) add_individual_race(tag, "White");
if (race_list["Asian Indian"] == true) add_individual_race(tag, "Asian Indian");
if (race_list["Chinese"] == true) add_individual_race(tag, "Chinese");
if (race_list["Filipino"] == true) add_individual_race(tag, "Filipino");
if (race_list["Japanese"] == true) add_individual_race(tag, "Japanese");
if (race_list["Korean"] == true) add_individual_race(tag, "Korean");
if (race_list["Vietnamese"] == true) add_individual_race(tag, "Vietnamese");
if (race_list["Other Asian"] == true) add_individual_race(tag, "Other Asian");
if (race_list["Unknown Asian"] == true) add_individual_race(tag, "Unknown Asian");
if (race_list["Chamorro"] == true) add_individual_race(tag, "Chamorro");
if (race_list["Guamanian"] == true) add_individual_race(tag, "Guamanian");
if (race_list["Native Hawaiian"] == true) add_individual_race(tag, "Native Hawaiian");
if (race_list["Samoan"] == true) add_individual_race(tag, "Samoan");
if (race_list["Unknown South Pacific Islander"] == true) add_individual_race(tag, "Unknown South Pacific Islander");
}
function add_individual_race(tag, race) {
race_tag = doc.createElement("raceCode");
race_tag.setAttribute("displayName", race);
cv = get_code_for_race(race);
race_tag.setAttribute("code", cv.code );
race_tag.setAttribute("codeSystemName", cv.code_system);
if (cv.id) race_tag.setAttribute("id", cv.id);
if (cv.xsi_type) race_tag.setAttribute("xsi:type", cv.xsi_type);
if (cv.ns) race_tag.setAttribute("xmlns:xsi", cv.ns);
tag.appendChild(race_tag);
}
function add_clinical_observations(tag,
height, height_unit,
weight, weight_unit,
consanguinity,
diseases,
cause_of_death,
twin_status,
adopted_flag,
active_flag)
{
var subjectOfTwo_tag = doc.createElement("subjectof2");
tag.appendChild(subjectOfTwo_tag);
add_twin_tag(subjectOfTwo_tag, twin_status);
add_adopted_tag(subjectOfTwo_tag, adopted_flag);
add_active_tag(subjectOfTwo_tag, active_flag);
add_height(subjectOfTwo_tag, height, height_unit);
add_weight(subjectOfTwo_tag, weight, weight_unit);
add_consanguinity(subjectOfTwo_tag, consanguinity);
add_diseases(subjectOfTwo_tag, diseases);
add_cause_of_death(subjectOfTwo_tag, cause_of_death);
}
function add_twin_tag(tag, twin_status) {
if (twin_status == null || twin_status == "") return;
if (!(twin_status == "IDENTICAL" || twin_status == "FRATERNAL")) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
if (twin_status == "IDENTICAL") {
code_tag.setAttribute("displayName", "Identical twin (person)");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.IDENTICAL_TWIN);
} else if (twin_status == "FRATERNAL") {
code_tag.setAttribute("displayName", "Fraternal twin (person)");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.FRATERNAL_TWIN);
}
observation_tag.appendChild(code_tag);
}
function add_adopted_tag(tag, adopted_tag) {
if (adopted_tag == null || !(adopted_tag == "true" || adopted_tag == true)) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "adopted");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.ADOPTED);
observation_tag.appendChild(code_tag);
}
function add_active_tag(tag, active_tag) {
if (active_tag == null) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Physically Active");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.PHYSICALLY_ACTIVE);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", active_tag);
observation_tag.appendChild(value_tag);
}
function add_height(tag, height, height_unit) {
if (height == null || height == "") return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "height");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.HEIGHT);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", height);
value_tag.setAttribute("unit", height_unit);
observation_tag.appendChild(value_tag);
}
function add_weight(tag, weight, weight_unit) {
if (weight == null || weight == "") return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "weight");
code_tag.setAttribute("codeSystemName", "SNOMED_CT");
code_tag.setAttribute("code", SNOMED_CODE.WEIGHT);
observation_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
value_tag.setAttribute("value", weight);
value_tag.setAttribute("unit", weight_unit);
observation_tag.appendChild(value_tag);
}
function add_diseases(tag, diseases) {
if (diseases == null) return;
for (var i=0; i<diseases.length;i++) {
var disease_name = diseases[i]["Disease Name"];
var detailed_disease_name = diseases[i]["Detailed Disease Name"];
var disease_code_and_system = diseases[i]["Disease Code"];
if (!detailed_disease_name) detailed_disease_name = disease_name;
var age_at_diagnosis = diseases[i]["Age At Diagnosis"];
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
if (disease_code_and_system) {
var dcas = disease_code_and_system.split("-");
var disease_code_system = dcas[0];
var disease_code = dcas[1];
code_tag.setAttribute("codeSystemName", disease_code_system);
code_tag.setAttribute("code", disease_code);
var potential_detailed_disease_name = get_detailed_disease_name_from_code(disease_code);
if (potential_detailed_disease_name != null) detailed_disease_name = potential_detailed_disease_name;
// alert (potential_detailed_disease_name + "->" + detailed_disease_name);
}
code_tag.setAttribute("displayName", detailed_disease_name);
code_tag.setAttribute("originalText", detailed_disease_name);
// code_tag.setAttribute("codeSystemName", "SNOMED COMPLETE"); //
observation_tag.appendChild(code_tag);
var subject_tag = doc.createElement("subject");
observation_tag.appendChild(subject_tag);
var dataEstimatedAge_tag = doc.createElement("dataEstimatedAge");
subject_tag.appendChild(dataEstimatedAge_tag);
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("displayName", "Estimated Age");
new_code_tag.setAttribute("codeSystemName", "LOINC");
new_code_tag.setAttribute("code", LOINC_CODE.ESTIMATED_AGE);
dataEstimatedAge_tag.appendChild(new_code_tag);
add_estimated_age_tag(dataEstimatedAge_tag, age_at_diagnosis);
}
}
function add_estimated_age_tag(tag, estimated_age) {
var av = get_age_values_from_estimated_age(estimated_age);
if (estimated_age == "Pre-Birth") {
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("originalText", "pre-birth");
tag.appendChild(new_code_tag);
} else if (estimated_age == "Unknown") {
var new_code_tag = doc.createElement("code");
new_code_tag.setAttribute("originalText", "unknown");
tag.appendChild(new_code_tag);
} else {
// These estimates ages have high, low, and unit tags/attr
var new_value_tag = doc.createElement("value");
tag.appendChild(new_value_tag);
if (av && av.unit) {
new_value_tag.setAttribute("unit", av.unit);
}
if (av && av.low) {
var low_tag = doc.createElement("low");
low_tag.setAttribute("value", av.low);
new_value_tag.appendChild(low_tag);
}
if (av && av.high) {
var high_tag = doc.createElement("high");
high_tag.setAttribute("value", av.high);
new_value_tag.appendChild(high_tag);
}
}
}
function add_death_status (tag, cause_of_death) {
if (cause_of_death == null) return;
var deceasedIndCode_tag = doc.createElement("deceasedIndCode");
deceasedIndCode_tag.setAttribute("value", "true");
tag.appendChild(deceasedIndCode_tag);
}
function add_death_age(tag, estimated_death_age) {
if (estimated_death_age == null) return;
var subjectOfOne_tag = doc.createElement("subjectOf1");
tag.appendChild(subjectOfOne_tag);
var deceasedEstimatedAge_tag = doc.createElement("deceasedEstimatedAge");
subjectOfOne_tag.appendChild(deceasedEstimatedAge_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", "Age at Death");
code_tag.setAttribute("codeSystemName", "LOINC");
code_tag.setAttribute("code", LOINC_CODE.AGE_AT_DEATH);
deceasedEstimatedAge_tag.appendChild(code_tag);
var value_tag = doc.createElement("value");
add_estimated_age_tag(deceasedEstimatedAge_tag, estimated_death_age);
}
function add_cause_of_death(tag, cause_of_death) {
if (cause_of_death == null) return;
var observation_tag = doc.createElement("clinicalObservation");
tag.appendChild(observation_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", cause_of_death);
code_tag.setAttribute("originalText", cause_of_death);
code_tag.setAttribute("codeSystemName", "SNOMED COMPLETE");
observation_tag.appendChild(code_tag);
var sourceOf_tag = doc.createElement("sourceOf");
observation_tag.appendChild(sourceOf_tag);
var newcode_tag = doc.createElement("code");
newcode_tag.setAttribute("displayName", "death");
newcode_tag.setAttribute("codeSystemName", "SNOMED_CT");
newcode_tag.setAttribute("code", SNOMED_CODE.DEATH);
sourceOf_tag.appendChild(newcode_tag);
}
function add_relatives(tag, pi) {
if (pi.mother) add_individual_relative(tag, "Mother", "NMTH", pi.mother);
if (pi.father) add_individual_relative(tag, "Father", "NFTH", pi.father);
if (pi.maternal_grandmother) add_individual_relative(tag, "Maternal Grandmother", "MGRMTH", pi.maternal_grandmother);
if (pi.maternal_grandfather) add_individual_relative(tag, "Maternal Grandfather", "MGRFTH", pi.maternal_grandfather);
if (pi.paternal_grandmother) add_individual_relative(tag, "Paternal Grandmother", "PGRMTH", pi.paternal_grandmother);
if (pi.paternal_grandfather) add_individual_relative(tag, "Paternal Grandfather", "PGRFTH", pi.paternal_grandfather);
var i = 0;
while (pi['brother_' + i] != null) {
add_individual_relative(tag, "Brother", "NBRO", pi['brother_' + i]);
i++;
}
var i = 0;
while (pi['sister_' + i] != null) {
add_individual_relative(tag, "Sister", "NSIS", pi['sister_' + i]);
i++;
}
var i = 0;
while (pi['son_' + i] != null) {
add_individual_relative(tag, "Son", "SON", pi['son_' + i]);
i++;
}
var i = 0;
while (pi['daughter_' + i] != null) {
add_individual_relative(tag, "Daughter", "DAU", pi['daughter_' + i]);
i++;
}
var i = 0;
while (pi['maternal_aunt_' + i] != null) {
add_individual_relative(tag, "Maternal Aunt", "MAUNT", pi['maternal_aunt_' + i]);
i++;
}
var i = 0;
while (pi['maternal_uncle_' + i] != null) {
add_individual_relative(tag, "Maternal Uncle", "MUNCLE", pi['maternal_uncle_' + i]);
i++;
}
var i = 0;
while (pi['paternal_aunt_' + i] != null) {
add_individual_relative(tag, "Paternal Aunt", "PAUNT", pi['paternal_aunt_' + i]);
i++;
}
var i = 0;
while (pi['paternal_uncle_' + i] != null) {
add_individual_relative(tag, "Paternal Uncle", "PUNCLE", pi['paternal_uncle_' + i]);
i++;
}
var i = 0;
while (pi['maternal_cousin_' + i] != null) {
add_individual_relative(tag, "Maternal Cousin", "MCOUSN", pi['maternal_cousin_' + i]);
i++;
}
var i = 0;
while (pi['paternal_cousin_' + i] != null) {
add_individual_relative(tag, "Paternal Cousin", "PCOUSN", pi['paternal_cousin_' + i]);
i++;
}
var i = 0;
while (pi['niece_' + i] != null) {
add_individual_relative(tag, "Niece", "NIECE", pi['niece_' + i]);
i++;
}
var i = 0;
while (pi['nephew_' + i] != null) {
add_individual_relative(tag, "Nephew", "NEPHEW", pi['nephew_' + i]);
i++;
}
var i = 0;
while (pi['grandson_' + i] != null) {
add_individual_relative(tag, "Grandson", "GRDSON", pi['grandson_' + i]);
i++;
}
var i = 0;
while (pi['granddaughter_' + i] != null) {
add_individual_relative(tag, "GrandDaughter", "GRDDAU", pi['granddaughter_' + i]);
i++;
}
var i = 0;
while (pi['maternal_halfbrother_' + i] != null) {
add_individual_relative(tag, "Maternal Halfbrother", "MHBRO", pi['maternal_halfbrother_' + i]);
i++;
}
var i = 0;
while (pi['maternal_halfsister_' + i] != null) {
add_individual_relative(tag, "Maternal Halfsister", "MHSIS", pi['maternal_halfsister_' + i]);
i++;
}
var i = 0;
while (pi['paternal_halfbrother_' + i] != null) {
add_individual_relative(tag, "Paternal Halfbrother", "PHBRO", pi['paternal_halfbrother_' + i]);
i++;
}
var i = 0;
while (pi['paternal_halfsister_' + i] != null) {
add_individual_relative(tag, "Paternal Halfsister", "PHSIS", pi['paternal_halfsister_' + i]);
i++;
}
}
function add_individual_relative(tag, relative_type, code, relative) {
var relative_tag = doc.createElement("relative");
tag.appendChild(relative_tag);
var code_tag = doc.createElement("code");
code_tag.setAttribute("displayName", relative_type);
code_tag.setAttribute("codeSystemName", "HL7 Family History Model");
code_tag.setAttribute("code", code);
relative_tag.appendChild(code_tag);
var relationshipHolder_tag = doc.createElement("relationshipHolder");
relative_tag.appendChild(relationshipHolder_tag);
add_parent(relationshipHolder_tag, relative.parent_id);
add_gender(relationshipHolder_tag, relative.gender);
add_all_ethnic_groups(relationshipHolder_tag, relative.ethnicity);
add_all_races(relationshipHolder_tag, relative.race);
add_death_age(relationshipHolder_tag, relative.estimated_death_age);
add_clinical_observations(relationshipHolder_tag,
null, null,
null, null,
null,
relative["Health History"],
relative.detailed_cause_of_death,
relative.twin_status,
relative.adopted,
null
);
add_id(relationshipHolder_tag, relative.id);
add_name(relationshipHolder_tag, relative.name);
add_birthday(relationshipHolder_tag, relative.date_of_birth);
add_death_status(relationshipHolder_tag, relative.cause_of_death);
}
// Functions to convert between code systems and display names
function get_code_for_ethnicity(str) {
switch (str) {
case "Hispanic or Latino": return {code:"2135-2", code_system:"HL7-TBD", id:"1"};
case "Ashkenazi Jewish": return {code:"81706006", code_system:"SNOMED_CT", id:"2"};
case "Not Hispanic or Latino": return {code:"2186-5", code_system:"HL7-TBD", id:"3"};
case "Central American": return {code:"2155-0", code_system:"HL7", id:"4", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Cuban": return {code:"2182-4", code_system:"HL7", id:"5", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Dominican": return {code:"2184-0", code_system:"HL7", id:"6", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Mexican": return {code:"2148-5", code_system:"HL7", id:"7", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Other Hispanic": return {code:"1000000", code_system:"TBD", id:"8", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "Puerto Rican": return {code:"2180-8", code_system:"HL7", id:"9", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
case "South American": return {code:"2165-9", code_system:"HL7", id:"10", xsi_type:"hispanic-ethnicity-type", ns:XMLNS_SCHEMA};
}
return null;
}
function get_code_for_race(str) {
switch (str) {
case "American Indian or Alaska Native": return {code:"1002-5", code_system:"HL7", id:"1"};
case "Asian": return {code:"1000000", code_system:"TBD", id:"2"};
case "Black or African-American": return {code:"2054-5", code_system:"HL7", id:"3"};
case "Native Hawaiian or Other Pacific Islander": return {code:"1000001", code_system:"TBD", id:"4"};
case "White": return {code:"2106-3", code_system:"HL7", id:"5"};
case "Asian Indian": return {code:"2029-7", code_system:"HL7", id:"11"};
case "Chinese": return {code:"2034-7", code_system:"HL7", id:"12"};
case "Filipino": return {code:"2036-2", code_system:"HL7", id:"13"};
case "Japanese": return {code:"2039-6", code_system:"HL7", id:"14"};
case "Korean": return {code:"2040-4", code_system:"HL7", id:"15"};
case "Vietnamese": return {code:"2047-9", code_system:"HL7", id:"16"};
case "Other Asian": return {code:"186046006", code_system:"SNOMED", id:"17"};
case "Unknown Asian": return {code:"2028-9", code_system:"HL7", id:"18"};
case "Chamorro": return {code:"2088-3", code_system:"HL7", id:"21"};
case "Guamanian": return {code:"2087-5", code_system:"HL7", id:"22"};
case "Native Hawaiian": return {code:"2079-2", code_system:"HL7", id:"23"};
case "Samoan": return {code:"2080-0", code_system:"HL7", id:"24"};
case "Unknown South Pacific Islander": return {code:"2076-8", code_system:"HL7", id:"25"};
}
return null;
}
function get_age_values_from_estimated_age(age_at_diagnosis) {
switch (age_at_diagnosis) {
case "prebirth": return null;
case "newborn": return {unit:"day", low:"0", high:"28"};
case "infant": return {unit:"day", low:"29", high:"729"};
case "child": return {unit:"year", low:"2", high:"10"};
case "teen": return {unit:"year", low:"11", high:"19"};
case "twenties": return {unit:"year", low:"20", high:"29"};
case "thirties": return {unit:"year", low:"30", high:"39"};
case "fourties": return {unit:"year", low:"40", high:"49"};
case "fifties": return {unit:"year", low:"50", high:"59"};
case "senior": return {unit:"year", low:"60", high:null};
case "unknown": return null;
}
return null;
}
function save_document(save_link, output_string, filename) {
if (isIE10) {
var blobObject = new Blob([output_string]);
window.navigator.msSaveBlob(blobObject, filename); // The user only has the option of clicking the Save button.
} else {
save_link.attr("href", "data:application/xml," + output_string ).attr("download", filename);
}
}
// function get_detailed_disease_name_from_code(disease_code) moved to load_xml.js
//// Helper to detect IE10
var isIE10 = false;
/*@cc_on
if (/^10/.test(@_jscript_version)) {
isIE10 = true;
}
@*/
| Fixed a bug n GOOGLE Drive save
| js/save_xml.js | Fixed a bug n GOOGLE Drive save | <ide><path>s/save_xml.js
<ide> output_string = get_xml_string();
<ide> filename = get_filename(personal_information);
<ide> // this is an aysncronous call, we need to improve the user experience here somehow.
<del> gapi.auth.authorize( {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false}, googlePostAuthSave);
<add> gapi.auth.authorize( {'client_id': GOOGLE_CLIENT_ID, 'scope': GOOGLE_SCOPES, 'immediate': false}, googlePostAuthSave);
<ide> });
<ide> $("#save_to_google_drive").append(button);
<ide> |
|
Java | apache-2.0 | 703acc8f65cd2b322eb1812712c1618ad7e1b808 | 0 | ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf | /*
Copyright 2013, 2016 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import nl.nn.adapterframework.configuration.IbisContext;
import org.apache.commons.digester.substitution.VariableExpander;
import org.apache.log4j.Logger;
/**
* Singleton class that has the constant values for this application. <br/>
* <p>When an instance is created, it tries to load the properties file specified
* by the <code>propertiesFileName</code> field</p>
* <p>If a property exits with the name <code>ADDITIONAL.PROPERTIES.FILE</code>
* that file is loaded also</p>
* @author Johan Verrips
*
*/
public final class AppConstants extends Properties implements Serializable{
private Logger log = LogUtil.getLogger(this);
public final static String propertiesFileName="AppConstants.properties";
private static AppConstants self=null;
private String additionalPropertiesFileKey="ADDITIONAL.PROPERTIES.FILE";
private VariableExpander variableExpander;
private static Properties propertyPlaceholderConfigurerProperties = new Properties();
// private final static Properties baseProperties = new Properties();
// static {
// baseProperties.put("hostname", Misc.getHostname());
// }
private AppConstants() {
super();
// putAll(baseProperties);
load(null, null, propertiesFileName);
}
private AppConstants(ClassLoader classLoader) {
super();
// putAll(baseProperties);
load(classLoader, null, propertiesFileName);
putAll(propertyPlaceholderConfigurerProperties);
}
private AppConstants(String directory) {
super();
load(null, directory, propertiesFileName);
putAll(propertyPlaceholderConfigurerProperties);
}
/**
* Retrieve an instance of this singleton
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance() {
if (self==null) {
self=new AppConstants();
}
return self;
}
/**
* Retrieve an instance based on a ClassLoader. This should be used by
* classes which are part of the Ibis configuration (like pipes and senders)
* because the configuration might be loaded from outside the webapp
* classpath. Hence the Thread.currentThread().getContextClassLoader() at
* the time the class was instantiated should be used.
*
* @see IbisContext#init()
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance(ClassLoader classLoader) {
return new AppConstants(classLoader);
}
/**
* Retrieve an instance based on a directory (not a singleton)
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance(String directory) {
return new AppConstants(directory);
}
/**
Very similar to <code>System.getProperty</code> except
that the {@link SecurityException} is hidden.
@param key The key to search for.
@return the string value of the system property, or the default
value if there is no property with that key.
@since 1.1 */
private String getSystemProperty(String key) {
try {
return System.getProperty(key);
} catch (Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
log.warn("Was not allowed to read system property [" + key + "]: "+ e.getMessage());
return null;
}
}
/**
* the method is like the <code>getProperty</code>, but provides functionality to resolve <code>${variable}</code>
* syntaxis. It uses the AppConstants values and systemvalues to resolve the variables, and does this recursively.
* @see nl.nn.adapterframework.util.StringResolver
*/
public String getResolvedProperty(String key) {
String value = null;
value=getSystemProperty(key); // first try custom properties
if (value==null) {
value = getProperty(key); // then try DeploymentSpecifics and appConstants
}
if (value != null) {
try {
String result=StringResolver.substVars(value, this);
if (log.isDebugEnabled()) {
if (!value.equals(result)){
log.debug("resolved key ["+key+"], value ["+value+"] to ["+result+"]");
}
}
return result;
} catch (IllegalArgumentException e) {
log.error("Bad option value [" + value + "].", e);
return value;
}
} else {
if (log.isDebugEnabled()) log.debug("getResolvedProperty: key ["+key+"] resolved to value ["+value+"]");
return null;
}
}
/**
* Creates a tokenizer from the values of this key. As a sepearator the "," is used.
* Uses the {@link #getResolvedProperty(String)} method.
* Can be used to process lists of values.
*/
public StringTokenizer getTokenizer(String key) {
return new StringTokenizer(getResolvedProperty(key), ",");
}
/**
* Creates a tokenizer from the values of this key.
* Uses the {@link #getResolvedProperty(String)} method.
* Can be used to process lists of values.
*/
public StringTokenizer getTokenizer(String key, String defaults) {
String list = getResolvedProperty(key);
if (list==null)
list = defaults;
return new StringTokenizer(list, ",");
}
/**
* Load the contents of a propertiesfile.
* <p>Optionally, this may be a comma-seperated list of files to load, e.g.
* <code><pre>log4j.properties,deploymentspecifics.properties</pre></code>
* which will cause both files to be loaded. Trimming of the filename will take place,
* so you may also specify <code><pre>log4j.properties, deploymentspecifics.properties</pre></code>
* </p>
*/
private synchronized void load(ClassLoader classLoader, String directory, String filename) {
StringTokenizer tokenizer = new StringTokenizer(filename, ",");
while (tokenizer.hasMoreTokens()) {
String theFilename= tokenizer.nextToken().trim();
try {
if (StringResolver.needsResolution(theFilename)) {
Properties props = Misc.getEnvironmentVariables();
props.putAll(System.getProperties());
theFilename = StringResolver.substVars(theFilename, props);
}
InputStream is = null;
if (directory != null) {
File file = new File(directory + "/" + theFilename);
if (file.exists()) {
is = new FileInputStream(file);
} else {
log.debug("cannot find file ["+theFilename+"] to load additional properties from, ignoring");
}
}
URL url = null;
if (is == null) {
url = ClassUtils.getResourceURL(classLoader, theFilename);
if (url == null) {
log.debug("cannot find resource ["+theFilename+"] to load additional properties from, ignoring");
} else {
is = url.openStream();
}
}
if (is != null) {
load(is);
if (url != null) {
log.info("Application constants loaded from url [" + url.toString() + "]");
} else {
log.info("Application constants loaded from file [" + theFilename + "]");
}
if (getProperty(additionalPropertiesFileKey) != null) {
// prevent reloading of the same file over and over again
String loadFile = getProperty(additionalPropertiesFileKey);
this.remove(additionalPropertiesFileKey);
load(classLoader, directory, loadFile);
}
}
} catch (IOException e) {
log.error("error reading [" + propertiesFileName + "]", e);
}
}
}
public void setPropertyPlaceholderConfigurerProperty(String name, String value) {
self.put(name, value);
propertyPlaceholderConfigurerProperties.put(name, value);
}
public String toXml() {
return toXml(false);
}
public String toXml(boolean resolve) {
Enumeration enumeration=this.keys();
XmlBuilder xmlh=new XmlBuilder("applicationConstants");
XmlBuilder xml=new XmlBuilder("properties");
xmlh.addSubElement(xml);
while (enumeration.hasMoreElements()){
String propName=(String)enumeration.nextElement();
XmlBuilder p=new XmlBuilder("property");
p.addAttribute("name", propName);
if (resolve) {
p.setValue(this.getResolvedProperty(propName));
} else {
p.setValue(this.getProperty(propName));
}
xml.addSubElement(p);
}
return xmlh.toXML();
}
/**
* Gets a <code>String</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return String
*/
public String getString(String key, String dfault){
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return ob;
}
/**
* Gets a <code>boolean</code> value
* Returns "true" if the retrieved value is "true", otherwise "false"
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return double
*/
public boolean getBoolean(String key, boolean dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return ob.equalsIgnoreCase("true");
}
/**
* Gets an <code>int</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return int
*/
public int getInt(String key, int dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null) return dfault;
return Integer.parseInt(ob);
}
/**
* Gets a <code>long</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return long
*/
public long getLong(String key, long dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return Long.parseLong(ob);
}
/**
* Gets a <code>double</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return double
*/
public double getDouble(String key, double dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return Double.parseDouble(ob);
}
/*
* The variableExpander is set from the SpringContext.
*/
public void setVariableExpander(VariableExpander expander) {
variableExpander = expander;
}
public VariableExpander getVariableExpander() {
return variableExpander;
}
}
| core/src/main/java/nl/nn/adapterframework/util/AppConstants.java | /*
Copyright 2013, 2016 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import nl.nn.adapterframework.configuration.IbisContext;
import org.apache.commons.digester.substitution.VariableExpander;
import org.apache.log4j.Logger;
/**
* Singleton class that has the constant values for this application. <br/>
* <p>When an instance is created, it tries to load the properties file specified
* by the <code>propertiesFileName</code> field</p>
* <p>If a property exits with the name <code>ADDITIONAL.PROPERTIES.FILE</code>
* that file is loaded also</p>
* @author Johan Verrips
*
*/
public final class AppConstants extends Properties implements Serializable{
private Logger log = LogUtil.getLogger(this);
public final static String propertiesFileName="AppConstants.properties";
private static AppConstants self=null;
private String additionalPropertiesFileKey="ADDITIONAL.PROPERTIES.FILE";
private VariableExpander variableExpander;
private static Properties propertyPlaceholderConfigurerProperties = new Properties();
private final static Properties baseProperties = new Properties();
static {
baseProperties.put("hostname", Misc.getHostname());
}
private AppConstants() {
super();
putAll(baseProperties);
load(null, null, propertiesFileName);
}
private AppConstants(ClassLoader classLoader) {
super();
putAll(baseProperties);
load(classLoader, null, propertiesFileName);
putAll(propertyPlaceholderConfigurerProperties);
}
private AppConstants(String directory) {
super();
load(null, directory, propertiesFileName);
putAll(propertyPlaceholderConfigurerProperties);
}
/**
* Retrieve an instance of this singleton
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance() {
if (self==null) {
self=new AppConstants();
}
return self;
}
/**
* Retrieve an instance based on a ClassLoader. This should be used by
* classes which are part of the Ibis configuration (like pipes and senders)
* because the configuration might be loaded from outside the webapp
* classpath. Hence the Thread.currentThread().getContextClassLoader() at
* the time the class was instantiated should be used.
*
* @see IbisContext#init()
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance(ClassLoader classLoader) {
return new AppConstants(classLoader);
}
/**
* Retrieve an instance based on a directory (not a singleton)
* @return AppConstants instance
*/
public static synchronized AppConstants getInstance(String directory) {
return new AppConstants(directory);
}
/**
Very similar to <code>System.getProperty</code> except
that the {@link SecurityException} is hidden.
@param key The key to search for.
@return the string value of the system property, or the default
value if there is no property with that key.
@since 1.1 */
private String getSystemProperty(String key) {
try {
return System.getProperty(key);
} catch (Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
log.warn("Was not allowed to read system property [" + key + "]: "+ e.getMessage());
return null;
}
}
/**
* the method is like the <code>getProperty</code>, but provides functionality to resolve <code>${variable}</code>
* syntaxis. It uses the AppConstants values and systemvalues to resolve the variables, and does this recursively.
* @see nl.nn.adapterframework.util.StringResolver
*/
public String getResolvedProperty(String key) {
String value = null;
value=getSystemProperty(key); // first try custom properties
if (value==null) {
value = getProperty(key); // then try DeploymentSpecifics and appConstants
}
if (value != null) {
try {
String result=StringResolver.substVars(value, this);
if (log.isDebugEnabled()) {
if (!value.equals(result)){
log.debug("resolved key ["+key+"], value ["+value+"] to ["+result+"]");
}
}
return result;
} catch (IllegalArgumentException e) {
log.error("Bad option value [" + value + "].", e);
return value;
}
} else {
if (log.isDebugEnabled()) log.debug("getResolvedProperty: key ["+key+"] resolved to value ["+value+"]");
return null;
}
}
/**
* Creates a tokenizer from the values of this key. As a sepearator the "," is used.
* Uses the {@link #getResolvedProperty(String)} method.
* Can be used to process lists of values.
*/
public StringTokenizer getTokenizer(String key) {
return new StringTokenizer(getResolvedProperty(key), ",");
}
/**
* Creates a tokenizer from the values of this key.
* Uses the {@link #getResolvedProperty(String)} method.
* Can be used to process lists of values.
*/
public StringTokenizer getTokenizer(String key, String defaults) {
String list = getResolvedProperty(key);
if (list==null)
list = defaults;
return new StringTokenizer(list, ",");
}
/**
* Load the contents of a propertiesfile.
* <p>Optionally, this may be a comma-seperated list of files to load, e.g.
* <code><pre>log4j.properties,deploymentspecifics.properties</pre></code>
* which will cause both files to be loaded. Trimming of the filename will take place,
* so you may also specify <code><pre>log4j.properties, deploymentspecifics.properties</pre></code>
* </p>
*/
private synchronized void load(ClassLoader classLoader, String directory, String filename) {
StringTokenizer tokenizer = new StringTokenizer(filename, ",");
while (tokenizer.hasMoreTokens()) {
String theFilename= tokenizer.nextToken().trim();
try {
if (StringResolver.needsResolution(theFilename)) {
Properties props = Misc.getEnvironmentVariables();
props.putAll(System.getProperties());
theFilename = StringResolver.substVars(theFilename, props);
}
InputStream is = null;
if (directory != null) {
File file = new File(directory + "/" + theFilename);
if (file.exists()) {
is = new FileInputStream(file);
} else {
log.debug("cannot find file ["+theFilename+"] to load additional properties from, ignoring");
}
}
URL url = null;
if (is == null) {
url = ClassUtils.getResourceURL(classLoader, theFilename);
if (url == null) {
log.debug("cannot find resource ["+theFilename+"] to load additional properties from, ignoring");
} else {
is = url.openStream();
}
}
if (is != null) {
load(is);
if (url != null) {
log.info("Application constants loaded from url [" + url.toString() + "]");
} else {
log.info("Application constants loaded from file [" + theFilename + "]");
}
if (getProperty(additionalPropertiesFileKey) != null) {
// prevent reloading of the same file over and over again
String loadFile = getProperty(additionalPropertiesFileKey);
this.remove(additionalPropertiesFileKey);
load(classLoader, directory, loadFile);
}
}
} catch (IOException e) {
log.error("error reading [" + propertiesFileName + "]", e);
}
}
}
public void setPropertyPlaceholderConfigurerProperty(String name, String value) {
self.put(name, value);
propertyPlaceholderConfigurerProperties.put(name, value);
}
public String toXml() {
return toXml(false);
}
public String toXml(boolean resolve) {
Enumeration enumeration=this.keys();
XmlBuilder xmlh=new XmlBuilder("applicationConstants");
XmlBuilder xml=new XmlBuilder("properties");
xmlh.addSubElement(xml);
while (enumeration.hasMoreElements()){
String propName=(String)enumeration.nextElement();
XmlBuilder p=new XmlBuilder("property");
p.addAttribute("name", propName);
if (resolve) {
p.setValue(this.getResolvedProperty(propName));
} else {
p.setValue(this.getProperty(propName));
}
xml.addSubElement(p);
}
return xmlh.toXML();
}
/**
* Gets a <code>String</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return String
*/
public String getString(String key, String dfault){
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return ob;
}
/**
* Gets a <code>boolean</code> value
* Returns "true" if the retrieved value is "true", otherwise "false"
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return double
*/
public boolean getBoolean(String key, boolean dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return ob.equalsIgnoreCase("true");
}
/**
* Gets an <code>int</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return int
*/
public int getInt(String key, int dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null) return dfault;
return Integer.parseInt(ob);
}
/**
* Gets a <code>long</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return long
*/
public long getLong(String key, long dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return Long.parseLong(ob);
}
/**
* Gets a <code>double</code> value
* Uses the {@link #getResolvedProperty(String)} method.
* @param key the Key
* @param dfault the default value
* @return double
*/
public double getDouble(String key, double dfault) {
String ob = this.getResolvedProperty(key);
if (ob == null)return dfault;
return Double.parseDouble(ob);
}
/*
* The variableExpander is set from the SpringContext.
*/
public void setVariableExpander(VariableExpander expander) {
variableExpander = expander;
}
public VariableExpander getVariableExpander() {
return variableExpander;
}
}
| Reverse "Add hostname property to AppConstants properties" | core/src/main/java/nl/nn/adapterframework/util/AppConstants.java | Reverse "Add hostname property to AppConstants properties" | <ide><path>ore/src/main/java/nl/nn/adapterframework/util/AppConstants.java
<ide> private VariableExpander variableExpander;
<ide> private static Properties propertyPlaceholderConfigurerProperties = new Properties();
<ide>
<del> private final static Properties baseProperties = new Properties();
<del> static {
<del> baseProperties.put("hostname", Misc.getHostname());
<del> }
<add>// private final static Properties baseProperties = new Properties();
<add>// static {
<add>// baseProperties.put("hostname", Misc.getHostname());
<add>// }
<ide>
<ide> private AppConstants() {
<ide> super();
<del> putAll(baseProperties);
<add>// putAll(baseProperties);
<ide> load(null, null, propertiesFileName);
<ide> }
<ide>
<ide> private AppConstants(ClassLoader classLoader) {
<ide> super();
<del> putAll(baseProperties);
<add>// putAll(baseProperties);
<ide> load(classLoader, null, propertiesFileName);
<ide> putAll(propertyPlaceholderConfigurerProperties);
<ide> } |
|
Java | bsd-3-clause | 3b3bfd04917acdad95533922ed42b466ae03cf84 | 0 | johannes85/core | /* This class is part of the XP framework's EAS connectivity
*
* $Id$
*/
package net.xp_framework.easc.protocol.standard;
import net.xp_framework.easc.protocol.standard.MessageType;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Message header
*
* A header consists of the following elements:
* <ul>
* <li>
* A magic number, constructed from the crc32 checksum of the string "xrmi"
* (0x3c872747 or 1015490375), packed into 4 bytes using pack("N", $magic).
* "N" stands for 'unsigned long (always 32 bit, big endian byte order)'.
* </li>
* <li>
* The protocol major version, as one byte
* </li>
* <li>
* The protocol minor version, as one byte
* </li>
* <li>
* The message type, as one byte
* </li>
* <li>
* If the data is compressed, as one byte (TRUE or FALSE)
* </li>
* <li>
* The data length packed into 4 bytes using pack("N", $length)
* </li>
* </ul>
*
* The header is 12 bytes long.
*
* @see http://php.net/pack
* @see http://php.net/crc32
*/
public class Header {
public static final int DEFAULT_MAGIC_NUMBER= 0x3c872747;
private int magicNumber;
private byte versionMajor;
private byte versionMinor;
private MessageType messageType;
private boolean compressed;
private int dataLength;
/**
* Constructor
*
* @access public
* @param int magic number
* @param byte version major
* @param byte version minor
* @param net.xp_framework.easc.protocol.standard.MessageType message type
* @param boolean compressed
* @param int data length
* @throws java.lang.NullPointerException if messageType is null
*/
public Header(
int magicNumber,
byte versionMajor,
byte versionMinor,
MessageType messageType,
boolean compressed,
int dataLength
) throws NullPointerException {
if (null == (this.messageType= messageType)) {
throw new NullPointerException("Messagetype may not be null");
}
this.magicNumber= magicNumber;
this.versionMajor= versionMajor;
this.versionMinor= versionMinor;
this.compressed= compressed;
this.dataLength= dataLength;
}
/**
* Reads and constructs a header object from a given input stream
*
* @static
* @access public
* @param java.io.DataInputStream in
* @return net.xp_framework.easc.protocol.standard.Header
* @throws java.io.IOException
*/
public static Header readFrom(DataInputStream in) throws IOException {
return new Header(
in.readInt(),
in.readByte(),
in.readByte(),
MessageType.valueOf(in.readByte()),
in.readBoolean(),
in.readInt()
);
}
/**
* Writes this header object to a given output stream
*
* @access public
* @param java.io.DataOutputStream out
* @return int number of bytes written
* @throws java.io.IOException
*/
public int writeTo(DataOutputStream out) throws IOException {
int written= out.size();
out.writeInt(this.magicNumber);
out.writeByte(this.versionMajor);
out.writeByte(this.versionMinor);
out.writeByte(this.messageType.ordinal());
out.writeBoolean(this.compressed);
out.writeInt(this.dataLength);
return out.size() - written;
}
/**
* Creates a string representation of this object
*
* @access public
* @return String
*/
@Override public String toString() {
return (
this.getClass().getName() + "[" + this.magicNumber + "]@{\n" +
" [Version.Major ] " + this.versionMajor + "\n" +
" [Version.Minor ] " + this.versionMinor + "\n" +
" [Message.Type ] " + this.messageType + "\n" +
" [Data.Compressed ] " + this.compressed + "\n" +
" [Data.Length ] " + this.dataLength + "\n" +
"}"
);
}
/**
* Tests whether a given object is equal to this object. Two headers
* are considered equal when all their members are equal.
*
* @access public
* @param lang.Object cmp
* @return boolean
*/
@Override public boolean equals(Object cmp) {
if (!(cmp instanceof Header)) return false; // Short-cuircuit this
Header h= (Header)cmp;
return (
(this.magicNumber == h.magicNumber) &&
(this.versionMajor == h.versionMajor) &&
(this.versionMinor == h.versionMinor) &&
(this.messageType.equals(h.messageType)) &&
(this.compressed == h.compressed) &&
(this.dataLength == h.dataLength)
);
}
/**
* Set magic number
*
* @access public
* @param int number
*/
public void setMagicNumber(int number) {
this.magicNumber= number;
}
/**
* Set version major number
*
* @access public
* @param byte version major number
*/
public void setVersionMajor(byte versionMajor) {
this.versionMajor= versionMajor;
}
/**
* Set version minor number
*
* @access public
* @param byte version minor number
*/
public void setVersionMinor(byte versionMinor) {
this.versionMinor= versionMinor;
}
/**
* Set type of message
*
* @access public
* @param net.xp_framework.easc.protocol.standard.MessageType messageType
*/
public void setMessageType(MessageType messageType) {
this.messageType= messageType;
}
/**
* Set compressed flag
*
* @access public
* @param boolean compressed
*/
public void setCompressed(boolean compressed) {
this.compressed= compressed;
}
/**
* Set data length
*
* @access public
* @param int data length
*/
public void setDataLength(int dataLength) {
this.dataLength= dataLength;
}
/**
* Set magic number
*
* @access public
* @return int
*/
public int getMagicNumber() {
return this.magicNumber;
}
/**
* Return version major number
*
* @access public
* @return byte version major
*/
public byte getVersionMajor() {
return this.versionMajor;
}
/**
* Return version minor number
*
* @access public
* @return byte version minor
*/
public byte getVersionMinor() {
return this.versionMinor;
}
/**
* Return type of message
*
* @access public
* @return net.xp_framework.easc.protocol.standard.MessageType messageType
*/
public MessageType getMessageType() {
return this.messageType;
}
/**
* Return data length
*
* @access public
* @return int data length
*/
public int getDataLength() {
return this.dataLength;
}
/**
* Return compressed flag
*
* @access public
* @return boolean compressed
*/
public boolean getCompressed() {
return this.compressed;
}
}
| experiments/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Header.java | /* This class is part of the XP framework's EAS connectivity
*
* $Id$
*/
package net.xp_framework.easc.protocol.standard;
import net.xp_framework.easc.protocol.standard.MessageType;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Message header
*
*/
public class Header {
private int magicNumber;
private byte versionMajor;
private byte versionMinor;
private MessageType messageType;
private boolean compressed;
private int dataLength;
/**
* Constructor
*
* @access public
* @param int magic number
* @param byte version major
* @param byte version minor
* @param net.xp_framework.easc.protocol.standard.MessageType message type
* @param boolean compressed
* @param int data length
* @throws java.lang.NullPointerException if messageType is null
*/
public Header(
int magicNumber,
byte versionMajor,
byte versionMinor,
MessageType messageType,
boolean compressed,
int dataLength
) throws NullPointerException {
if (null == (this.messageType= messageType)) {
throw new NullPointerException("Messagetype may not be null");
}
this.magicNumber= magicNumber;
this.versionMajor= versionMajor;
this.versionMinor= versionMinor;
this.compressed= compressed;
this.dataLength= dataLength;
}
/**
* Reads and constructs a header object from a given input stream
*
* @static
* @access public
* @param java.io.DataInputStream in
* @return net.xp_framework.easc.protocol.standard.Header
* @throws java.io.IOException
*/
public static Header readFrom(DataInputStream in) throws IOException {
return new Header(
in.readInt(),
in.readByte(),
in.readByte(),
MessageType.valueOf(in.readByte()),
in.readBoolean(),
in.readInt()
);
}
/**
* Writes this header object to a given output stream
*
* @access public
* @param java.io.DataOutputStream out
* @return int number of bytes written
* @throws java.io.IOException
*/
public int writeTo(DataOutputStream out) throws IOException {
int written= out.size();
out.writeInt(this.magicNumber);
out.writeByte(this.versionMajor);
out.writeByte(this.versionMinor);
out.writeByte(this.messageType.ordinal());
out.writeBoolean(this.compressed);
out.writeInt(this.dataLength);
return out.size() - written;
}
/**
* Creates a string representation of this object
*
* @access public
* @return String
*/
@Override public String toString() {
return (
this.getClass().getName() + "[" + this.magicNumber + "]@{\n" +
" [Version.Major ] " + this.versionMajor + "\n" +
" [Version.Minor ] " + this.versionMinor + "\n" +
" [Message.Type ] " + this.messageType + "\n" +
" [Data.Compressed ] " + this.compressed + "\n" +
" [Data.Length ] " + this.dataLength + "\n" +
"}"
);
}
/**
* Tests whether a given object is equal to this object. Two headers
* are considered equal when all their members are equal.
*
* @access public
* @param lang.Object cmp
* @return boolean
*/
@Override public boolean equals(Object cmp) {
if (!(cmp instanceof Header)) return false; // Short-cuircuit this
Header h= (Header)cmp;
return (
(this.magicNumber == h.magicNumber) &&
(this.versionMajor == h.versionMajor) &&
(this.versionMinor == h.versionMinor) &&
(this.messageType.equals(h.messageType)) &&
(this.compressed == h.compressed) &&
(this.dataLength == h.dataLength)
);
}
/**
* Set magic number
*
* @access public
* @param int number
*/
public void setMagicNumber(int number) {
this.magicNumber= number;
}
/**
* Set version major number
*
* @access public
* @param byte version major number
*/
public void setVersionMajor(byte versionMajor) {
this.versionMajor= versionMajor;
}
/**
* Set version minor number
*
* @access public
* @param byte version minor number
*/
public void setVersionMinor(byte versionMinor) {
this.versionMinor= versionMinor;
}
/**
* Set type of message
*
* @access public
* @param net.xp_framework.easc.protocol.standard.MessageType messageType
*/
public void setMessageType(MessageType messageType) {
this.messageType= messageType;
}
/**
* Set compressed flag
*
* @access public
* @param boolean compressed
*/
public void setCompressed(boolean compressed) {
this.compressed= compressed;
}
/**
* Set data length
*
* @access public
* @param int data length
*/
public void setDataLength(int dataLength) {
this.dataLength= dataLength;
}
/**
* Set magic number
*
* @access public
* @return int
*/
public int getMagicNumber() {
return this.magicNumber;
}
/**
* Return version major number
*
* @access public
* @return byte version major
*/
public byte getVersionMajor() {
return this.versionMajor;
}
/**
* Return version minor number
*
* @access public
* @return byte version minor
*/
public byte getVersionMinor() {
return this.versionMinor;
}
/**
* Return type of message
*
* @access public
* @return net.xp_framework.easc.protocol.standard.MessageType messageType
*/
public MessageType getMessageType() {
return this.messageType;
}
/**
* Return data length
*
* @access public
* @return int data length
*/
public int getDataLength() {
return this.dataLength;
}
/**
* Return compressed flag
*
* @access public
* @return boolean compressed
*/
public boolean getCompressed() {
return this.compressed;
}
}
| - Add api documentation
- Add DEFAULT_MAGIC_NUMBER "constant"
git-svn-id: 526f3b90ad6d9b1dfe840af828070ca3d99521ac@5533 d2cacbed-c0f6-0310-851a-9dad52fc623a
| experiments/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Header.java | - Add api documentation - Add DEFAULT_MAGIC_NUMBER "constant" | <ide><path>xperiments/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Header.java
<ide> /**
<ide> * Message header
<ide> *
<add> * A header consists of the following elements:
<add> * <ul>
<add> * <li>
<add> * A magic number, constructed from the crc32 checksum of the string "xrmi"
<add> * (0x3c872747 or 1015490375), packed into 4 bytes using pack("N", $magic).
<add> * "N" stands for 'unsigned long (always 32 bit, big endian byte order)'.
<add> * </li>
<add> * <li>
<add> * The protocol major version, as one byte
<add> * </li>
<add> * <li>
<add> * The protocol minor version, as one byte
<add> * </li>
<add> * <li>
<add> * The message type, as one byte
<add> * </li>
<add> * <li>
<add> * If the data is compressed, as one byte (TRUE or FALSE)
<add> * </li>
<add> * <li>
<add> * The data length packed into 4 bytes using pack("N", $length)
<add> * </li>
<add> * </ul>
<add> *
<add> * The header is 12 bytes long.
<add> *
<add> * @see http://php.net/pack
<add> * @see http://php.net/crc32
<ide> */
<ide> public class Header {
<add> public static final int DEFAULT_MAGIC_NUMBER= 0x3c872747;
<add>
<ide> private int magicNumber;
<ide> private byte versionMajor;
<ide> private byte versionMinor; |
|
Java | apache-2.0 | error: pathspec 'java/src/com/mechadev/holidays/Holiday.java' did not match any file(s) known to git
| c592e44bc7ef7a910cc9e55e5a300ed091b0ef8d | 1 | MechaDev/Mecha-Holidays | package com.mechadev.holidays;
public enum Holiday {
NEW_YEARS_DAY("New Years Day"),
INAUGURATION_DAY("Inauguration Day"),
MARTIN_LUTHER_KING_JR_DAY("Martin Luther King Jr Day"),
GEORGE_WASHINGTONS_BIRTHDAY("George Washington's Birthday"),
MEMORIAL_DAY("Memorial Day"),
INDEPENDENCE_DAY("Independence Day"),
LABOR_DAY("Labor Day"),
COLUMBUS_DAY("Columbus Day"),
VETERANS_DAY("Verterans Day"),
THANKSGIVING_DAY("Thanksgiving"),
CHRISTMAS_DAY("Christmas");
private final String name;
private Holiday(String name) { this.name = name; }
public String getName() { return name; }
}
| java/src/com/mechadev/holidays/Holiday.java |
US Federal Holidays included | java/src/com/mechadev/holidays/Holiday.java | <ide><path>ava/src/com/mechadev/holidays/Holiday.java
<add>package com.mechadev.holidays;
<add>
<add>
<add>public enum Holiday {
<add> NEW_YEARS_DAY("New Years Day"),
<add> INAUGURATION_DAY("Inauguration Day"),
<add> MARTIN_LUTHER_KING_JR_DAY("Martin Luther King Jr Day"),
<add> GEORGE_WASHINGTONS_BIRTHDAY("George Washington's Birthday"),
<add> MEMORIAL_DAY("Memorial Day"),
<add> INDEPENDENCE_DAY("Independence Day"),
<add> LABOR_DAY("Labor Day"),
<add> COLUMBUS_DAY("Columbus Day"),
<add> VETERANS_DAY("Verterans Day"),
<add> THANKSGIVING_DAY("Thanksgiving"),
<add> CHRISTMAS_DAY("Christmas");
<add>
<add> private final String name;
<add>
<add> private Holiday(String name) { this.name = name; }
<add>
<add> public String getName() { return name; }
<add>} |
||
Java | apache-2.0 | 7af43605811c147de2175408882d1dad61daa1a8 | 0 | cloudsmith/orientdb,cloudsmith/orientdb,cloudsmith/orientdb,cloudsmith/orientdb | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
import java.lang.reflect.Array;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.entity.OEntityManagerInternal;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.object.OObjectSerializerHelper;
@SuppressWarnings("unchecked")
public abstract class ORecordSerializerCSVAbstract extends ORecordSerializerStringAbstract {
public static final String FIELD_VALUE_SEPARATOR = ":";
protected abstract ORecordSchemaAware<?> newObject(ODatabaseRecord<?> iDatabase, String iClassName);
public Object fieldFromStream(final ODatabaseRecord<?> iDatabase, final OType iType, OClass iLinkedClass, OType iLinkedType,
final String iName, final String iValue, final DecimalFormatSymbols iUnusualSymbols) {
if (iValue == null)
return null;
switch (iType) {
case EMBEDDEDLIST:
case EMBEDDEDSET: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END COLLECTIONS CHARACTERS IF IT'S A COLLECTION
String value = iValue.startsWith("[") ? iValue.substring(1, iValue.length() - 1) : iValue;
Collection<Object> coll = iType == OType.EMBEDDEDLIST ? new ArrayList<Object>() : new HashSet<Object>();
if (value.length() == 0)
return coll;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
for (String item : items) {
if (iLinkedClass != null) {
// EMBEDDED OBJECT
if (item.length() > 2) {
item = item.substring(1, item.length() - 1);
coll.add(fromString(iDatabase, item, new ODocument(iDatabase, iLinkedClass.getName())));
}
} else if (item.length() > 0 && item.charAt(0) == OStringSerializerHelper.EMBEDDED) {
// EMBEDDED OBJECT
coll.add(OStringSerializerHelper.fieldTypeFromStream(iLinkedType, item.substring(1, item.length() - 1)));
} else {
// EMBEDDED LITERAL
if (iLinkedType == null)
throw new IllegalArgumentException(
"Linked type can't be null. Probably the serialized type has not stored the type along with data");
coll.add(OStringSerializerHelper.fieldTypeFromStream(iLinkedType, item));
}
}
return coll;
}
case LINKLIST:
case LINKSET: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END COLLECTIONS CHARACTERS IF IT'S A COLLECTION
String value = iValue.startsWith("[") ? iValue.substring(1, iValue.length() - 1) : iValue;
Collection<Object> coll = iType == OType.LINKLIST ? new ArrayList<Object>() : new HashSet<Object>();
if (value.length() == 0)
return coll;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
for (String item : items) {
// GET THE CLASS NAME IF ANY
int classSeparatorPos = value.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (classSeparatorPos > -1) {
String className = value.substring(1, classSeparatorPos);
if (className != null) {
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(className);
item = item.substring(classSeparatorPos + 1);
}
} else
item = item.substring(1);
coll.add(new ODocument(iDatabase, iLinkedClass != null ? iLinkedClass.getName() : null, new ORecordId(item)));
}
return coll;
}
case EMBEDDEDMAP: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END MAP CHARACTERS
String value = iValue.substring(1, iValue.length() - 1);
Map<String, Object> map = new HashMap<String, Object>();
if (value.length() == 0)
return map;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
// EMBEDDED LITERALS
String[] entry;
String mapValue;
for (String item : items) {
if (item != null && item.length() > 0) {
entry = item.split(OStringSerializerHelper.ENTRY_SEPARATOR);
if (entry.length > 0) {
mapValue = entry[1];
if (iLinkedType == null) {
if (mapValue.length() > 0) {
if (mapValue.startsWith(OStringSerializerHelper.LINK)) {
iLinkedType = OType.LINK;
// GET THE CLASS NAME IF ANY
int classSeparatorPos = value.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (classSeparatorPos > -1) {
String className = value.substring(1, classSeparatorPos);
if (className != null)
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(className);
}
} else if (mapValue.charAt(0) == OStringSerializerHelper.EMBEDDED) {
iLinkedType = OType.EMBEDDED;
} else if (Character.isDigit(mapValue.charAt(0)) || mapValue.charAt(0) == '+' || mapValue.charAt(0) == '-') {
iLinkedType = getNumber(iUnusualSymbols, mapValue);
} else if (mapValue.charAt(0) == '\'' || mapValue.charAt(0) == '"')
iLinkedType = OType.STRING;
} else
iLinkedType = OType.EMBEDDED;
}
map.put((String) OStringSerializerHelper.fieldTypeFromStream(OType.STRING, entry[0]), OStringSerializerHelper
.fieldTypeFromStream(iLinkedType, mapValue));
}
}
}
return map;
}
case LINK:
if (iValue.length() > 1) {
int pos = iValue.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (pos > -1)
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(iValue.substring(OStringSerializerHelper.LINK.length(), pos));
else
pos = 0;
// if (iLinkedClass == null)
// throw new IllegalArgumentException("Linked class not specified in ORID field: " + iValue);
ORecordId recId = new ORecordId(iValue.substring(pos + 1));
return new ODocument(iDatabase, iLinkedClass != null ? iLinkedClass.getName() : null, recId);
} else
return null;
default:
return OStringSerializerHelper.fieldTypeFromStream(iType, iValue);
}
}
public String fieldToStream(final ODocument iRecord, final ODatabaseRecord iDatabase,
final OUserObject2RecordHandler iObjHandler, final OType iType, final OClass iLinkedClass, final OType iLinkedType,
final String iName, final Object iValue, final Map<ORecordInternal<?>, ORecordId> iMarshalledRecords) {
StringBuilder buffer = new StringBuilder();
switch (iType) {
case EMBEDDED:
if (iValue instanceof ODocument)
buffer.append(toString((ODocument) iValue, null, iObjHandler, iMarshalledRecords));
else if (iValue != null)
buffer.append(iValue.toString());
break;
case LINK: {
linkToStream(buffer, iRecord, iValue);
break;
}
case EMBEDDEDLIST:
case EMBEDDEDSET: {
buffer.append(OStringSerializerHelper.COLLECTION_BEGIN);
int size = iValue instanceof Collection<?> ? ((Collection<Object>) iValue).size() : Array.getLength(iValue);
Iterator<Object> iterator = iValue instanceof Collection<?> ? ((Collection<Object>) iValue).iterator() : null;
Object o;
for (int i = 0; i < size; ++i) {
if (iValue instanceof Collection<?>)
o = iterator.next();
else
o = Array.get(iValue, i);
if (i > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
if (o instanceof ORecord<?>)
buffer.append(OStringSerializerHelper.EMBEDDED);
if (iLinkedClass != null) {
// EMBEDDED OBJECTS
ODocument record;
if (o != null) {
if (o instanceof ODocument)
record = (ODocument) o;
else
record = OObjectSerializerHelper.toStream(o, new ODocument(o.getClass().getSimpleName()),
iDatabase instanceof ODatabaseObjectTx ? ((ODatabaseObjectTx) iDatabase).getEntityManager()
: OEntityManagerInternal.INSTANCE, iLinkedClass, iObjHandler != null ? iObjHandler
: new OUserObject2RecordHandler() {
public Object getUserObjectByRecord(ORecordInternal<?> iRecord) {
return iRecord;
}
public ORecordInternal<?> getRecordByUserObject(Object iPojo, boolean iIsMandatory) {
return new ODocument(iLinkedClass);
}
});
buffer.append(toString(record, null, iObjHandler, iMarshalledRecords));
}
} else {
// EMBEDDED LITERALS
buffer.append(OStringSerializerHelper.fieldTypeToString(iLinkedType, o));
}
if (o instanceof ORecord<?>)
buffer.append(OStringSerializerHelper.EMBEDDED);
}
buffer.append(OStringSerializerHelper.COLLECTION_END);
break;
}
case EMBEDDEDMAP: {
buffer.append(OStringSerializerHelper.MAP_BEGIN);
int items = 0;
if (iLinkedClass != null) {
// EMBEDDED OBJECTS
ODocument record;
for (Entry<String, Object> o : ((Map<String, Object>) iValue).entrySet()) {
if (items > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
if (o != null) {
if (o instanceof ODocument)
record = (ODocument) o;
else
record = OObjectSerializerHelper.toStream(o, new ODocument(o.getClass().getSimpleName()),
iDatabase instanceof ODatabaseObjectTx ? ((ODatabaseObjectTx) iDatabase).getEntityManager()
: OEntityManagerInternal.INSTANCE, iLinkedClass, iObjHandler != null ? iObjHandler
: new OUserObject2RecordHandler() {
public Object getUserObjectByRecord(ORecordInternal<?> iRecord) {
return iRecord;
}
public ORecordInternal<?> getRecordByUserObject(Object iPojo, boolean iIsMandatory) {
return new ODocument(iLinkedClass);
}
});
buffer.append(OStringSerializerHelper.EMBEDDED);
buffer.append(toString(record, null, iObjHandler, iMarshalledRecords));
buffer.append(OStringSerializerHelper.EMBEDDED);
}
items++;
}
} else
// EMBEDDED LITERALS
for (Entry<String, Object> o : ((Map<String, Object>) iValue).entrySet()) {
if (items > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
buffer.append(OStringSerializerHelper.fieldTypeToString(OType.STRING, o.getKey()));
buffer.append(OStringSerializerHelper.ENTRY_SEPARATOR);
buffer.append(OStringSerializerHelper.fieldTypeToString(iLinkedType, o.getValue()));
items++;
}
buffer.append(OStringSerializerHelper.MAP_END);
break;
}
case LINKLIST:
case LINKSET: {
buffer.append(OStringSerializerHelper.COLLECTION_BEGIN);
int items = 0;
// LINKED OBJECTS
for (Object link : (Collection<Object>) iValue) {
if (items++ > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
linkToStream(buffer, iRecord, link);
}
buffer.append(OStringSerializerHelper.COLLECTION_END);
break;
}
default:
return OStringSerializerHelper.fieldTypeToString(iType, iValue);
}
return buffer.toString();
}
/**
* Parse a string returning the closer type. To avoid limit exceptions, for integer numbers are returned always LONG and for
* decimal ones always DOUBLE.
*
* @param iUnusualSymbols
* Localized decimal number separators
* @param iValue
* Value to parse
* @return OType.LONG for integers, OType.DOUBLE for decimals and OType.STRING for other
*/
public static OType getNumber(final DecimalFormatSymbols iUnusualSymbols, final String iValue) {
boolean integer = true;
char c;
for (int index = 0; index < iValue.length(); ++index) {
c = iValue.charAt(index);
if (c < '0' || c > '9')
if ((index == 0 && (c == '+' || c == '-')))
continue;
else if (c == iUnusualSymbols.getDecimalSeparator())
integer = false;
else {
return OType.STRING;
}
}
return integer ? OType.LONG : OType.DOUBLE;
}
/**
* Serialize the link.
*
* @param buffer
* @param iParentRecord
* @param iLinked
* Can be an instance of ORID or a Record<?>
*/
private void linkToStream(final StringBuilder buffer, final ORecordSchemaAware<?> iParentRecord, final Object iLinked) {
if (iLinked == null)
// NULL REFERENCE
return;
ORID rid;
buffer.append(OStringSerializerHelper.LINK);
if (iLinked instanceof ORID) {
// JUST THE REFERENCE
rid = (ORID) iLinked;
} else {
// RECORD
ORecordInternal<?> iLinkedRecord = (ORecordInternal<?>) iLinked;
rid = iLinkedRecord.getIdentity();
if (!rid.isValid()) {
// OVERWRITE THE DATABASE TO THE SAME OF PARENT ONE
iLinkedRecord.setDatabase(iParentRecord.getDatabase());
// STORE THE TRAVERSED OBJECT TO KNOW THE RECORD ID. CALL THIS VERSION TO AVOID CLEAR OF STACK IN THREAD-LOCAL
iLinkedRecord.getDatabase().save((ORecordInternal) iLinkedRecord);
}
if (iLinkedRecord instanceof ORecordSchemaAware<?>) {
final ORecordSchemaAware<?> schemaAwareRecord = (ORecordSchemaAware<?>) iLinkedRecord;
if (schemaAwareRecord.getClassName() != null) {
buffer.append(schemaAwareRecord.getClassName());
buffer.append(OStringSerializerHelper.CLASS_SEPARATOR);
}
}
}
if (rid.isValid())
buffer.append(rid.toString());
}
}
| core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
import java.lang.reflect.Array;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.entity.OEntityManagerInternal;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.object.OObjectSerializerHelper;
@SuppressWarnings("unchecked")
public abstract class ORecordSerializerCSVAbstract extends ORecordSerializerStringAbstract {
public static final String FIELD_VALUE_SEPARATOR = ":";
protected abstract ORecordSchemaAware<?> newObject(ODatabaseRecord<?> iDatabase, String iClassName);
public Object fieldFromStream(final ODatabaseRecord<?> iDatabase, final OType iType, OClass iLinkedClass, OType iLinkedType,
final String iName, final String iValue, final DecimalFormatSymbols iUnusualSymbols) {
if (iValue == null)
return null;
switch (iType) {
case EMBEDDEDLIST:
case EMBEDDEDSET: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END COLLECTIONS CHARACTERS
String value = iValue.substring(1, iValue.length() - 1);
Collection<Object> coll = iType == OType.EMBEDDEDLIST ? new ArrayList<Object>() : new HashSet<Object>();
if (value.length() == 0)
return coll;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
for (String item : items) {
if (iLinkedClass != null) {
// EMBEDDED OBJECT
if (item.length() > 2) {
item = item.substring(1, item.length() - 1);
coll.add(fromString(iDatabase, item, new ODocument(iDatabase, iLinkedClass.getName())));
}
} else if (item.length() > 0 && item.charAt(0) == OStringSerializerHelper.EMBEDDED) {
// EMBEDDED OBJECT
coll.add(OStringSerializerHelper.fieldTypeFromStream(iLinkedType, item.substring(1, item.length() - 1)));
} else {
// EMBEDDED LITERAL
if (iLinkedType == null)
throw new IllegalArgumentException(
"Linked type can't be null. Probably the serialized type has not stored the type along with data");
coll.add(OStringSerializerHelper.fieldTypeFromStream(iLinkedType, item));
}
}
return coll;
}
case LINKLIST:
case LINKSET: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END COLLECTIONS CHARACTERS
String value = iValue.substring(1, iValue.length() - 1);
Collection<Object> coll = iType == OType.LINKLIST ? new ArrayList<Object>() : new HashSet<Object>();
if (value.length() == 0)
return coll;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
for (String item : items) {
// GET THE CLASS NAME IF ANY
int classSeparatorPos = value.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (classSeparatorPos > -1) {
String className = value.substring(1, classSeparatorPos);
if (className != null) {
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(className);
item = item.substring(classSeparatorPos + 1);
}
} else
item = item.substring(1);
coll.add(new ODocument(iDatabase, iLinkedClass != null ? iLinkedClass.getName() : null, new ORecordId(item)));
}
return coll;
}
case EMBEDDEDMAP: {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END MAP CHARACTERS
String value = iValue.substring(1, iValue.length() - 1);
Map<String, Object> map = new HashMap<String, Object>();
if (value.length() == 0)
return map;
String[] items = OStringSerializerHelper.split(value, OStringSerializerHelper.RECORD_SEPARATOR_AS_CHAR);
// EMBEDDED LITERALS
String[] entry;
String mapValue;
for (String item : items) {
if (item != null && item.length() > 0) {
entry = item.split(OStringSerializerHelper.ENTRY_SEPARATOR);
if (entry.length > 0) {
mapValue = entry[1];
if (iLinkedType == null) {
if (mapValue.length() > 0) {
if (mapValue.startsWith(OStringSerializerHelper.LINK)) {
iLinkedType = OType.LINK;
// GET THE CLASS NAME IF ANY
int classSeparatorPos = value.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (classSeparatorPos > -1) {
String className = value.substring(1, classSeparatorPos);
if (className != null)
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(className);
}
} else if (mapValue.charAt(0) == OStringSerializerHelper.EMBEDDED) {
iLinkedType = OType.EMBEDDED;
} else if (Character.isDigit(mapValue.charAt(0)) || mapValue.charAt(0) == '+' || mapValue.charAt(0) == '-') {
iLinkedType = getNumber(iUnusualSymbols, mapValue);
} else if (mapValue.charAt(0) == '\'' || mapValue.charAt(0) == '"')
iLinkedType = OType.STRING;
} else
iLinkedType = OType.EMBEDDED;
}
map.put((String) OStringSerializerHelper.fieldTypeFromStream(OType.STRING, entry[0]), OStringSerializerHelper
.fieldTypeFromStream(iLinkedType, mapValue));
}
}
}
return map;
}
case LINK:
if (iValue.length() > 1) {
int pos = iValue.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
if (pos > -1)
iLinkedClass = iDatabase.getMetadata().getSchema().getClass(iValue.substring(OStringSerializerHelper.LINK.length(), pos));
else
pos = 0;
// if (iLinkedClass == null)
// throw new IllegalArgumentException("Linked class not specified in ORID field: " + iValue);
ORecordId recId = new ORecordId(iValue.substring(pos + 1));
return new ODocument(iDatabase, iLinkedClass != null ? iLinkedClass.getName() : null, recId);
} else
return null;
default:
return OStringSerializerHelper.fieldTypeFromStream(iType, iValue);
}
}
public String fieldToStream(final ODocument iRecord, final ODatabaseRecord iDatabase,
final OUserObject2RecordHandler iObjHandler, final OType iType, final OClass iLinkedClass, final OType iLinkedType,
final String iName, final Object iValue, final Map<ORecordInternal<?>, ORecordId> iMarshalledRecords) {
StringBuilder buffer = new StringBuilder();
switch (iType) {
case EMBEDDED:
if (iValue instanceof ODocument)
buffer.append(toString((ODocument) iValue, null, iObjHandler, iMarshalledRecords));
else if (iValue != null)
buffer.append(iValue.toString());
break;
case LINK: {
linkToStream(buffer, iRecord, iValue);
break;
}
case EMBEDDEDLIST:
case EMBEDDEDSET: {
buffer.append(OStringSerializerHelper.COLLECTION_BEGIN);
int size = iValue instanceof Collection<?> ? ((Collection<Object>) iValue).size() : Array.getLength(iValue);
Iterator<Object> iterator = iValue instanceof Collection<?> ? ((Collection<Object>) iValue).iterator() : null;
Object o;
for (int i = 0; i < size; ++i) {
if (iValue instanceof Collection<?>)
o = iterator.next();
else
o = Array.get(iValue, i);
if (i > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
if (o instanceof ORecord<?>)
buffer.append(OStringSerializerHelper.EMBEDDED);
if (iLinkedClass != null) {
// EMBEDDED OBJECTS
ODocument record;
if (o != null) {
if (o instanceof ODocument)
record = (ODocument) o;
else
record = OObjectSerializerHelper.toStream(o, new ODocument(o.getClass().getSimpleName()),
iDatabase instanceof ODatabaseObjectTx ? ((ODatabaseObjectTx) iDatabase).getEntityManager()
: OEntityManagerInternal.INSTANCE, iLinkedClass, iObjHandler != null ? iObjHandler
: new OUserObject2RecordHandler() {
public Object getUserObjectByRecord(ORecordInternal<?> iRecord) {
return iRecord;
}
public ORecordInternal<?> getRecordByUserObject(Object iPojo, boolean iIsMandatory) {
return new ODocument(iLinkedClass);
}
});
buffer.append(toString(record, null, iObjHandler, iMarshalledRecords));
}
} else {
// EMBEDDED LITERALS
buffer.append(OStringSerializerHelper.fieldTypeToString(iLinkedType, o));
}
if (o instanceof ORecord<?>)
buffer.append(OStringSerializerHelper.EMBEDDED);
}
buffer.append(OStringSerializerHelper.COLLECTION_END);
break;
}
case EMBEDDEDMAP: {
buffer.append(OStringSerializerHelper.MAP_BEGIN);
int items = 0;
if (iLinkedClass != null) {
// EMBEDDED OBJECTS
ODocument record;
for (Entry<String, Object> o : ((Map<String, Object>) iValue).entrySet()) {
if (items > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
if (o != null) {
if (o instanceof ODocument)
record = (ODocument) o;
else
record = OObjectSerializerHelper.toStream(o, new ODocument(o.getClass().getSimpleName()),
iDatabase instanceof ODatabaseObjectTx ? ((ODatabaseObjectTx) iDatabase).getEntityManager()
: OEntityManagerInternal.INSTANCE, iLinkedClass, iObjHandler != null ? iObjHandler
: new OUserObject2RecordHandler() {
public Object getUserObjectByRecord(ORecordInternal<?> iRecord) {
return iRecord;
}
public ORecordInternal<?> getRecordByUserObject(Object iPojo, boolean iIsMandatory) {
return new ODocument(iLinkedClass);
}
});
buffer.append(OStringSerializerHelper.EMBEDDED);
buffer.append(toString(record, null, iObjHandler, iMarshalledRecords));
buffer.append(OStringSerializerHelper.EMBEDDED);
}
items++;
}
} else
// EMBEDDED LITERALS
for (Entry<String, Object> o : ((Map<String, Object>) iValue).entrySet()) {
if (items > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
buffer.append(OStringSerializerHelper.fieldTypeToString(OType.STRING, o.getKey()));
buffer.append(OStringSerializerHelper.ENTRY_SEPARATOR);
buffer.append(OStringSerializerHelper.fieldTypeToString(iLinkedType, o.getValue()));
items++;
}
buffer.append(OStringSerializerHelper.MAP_END);
break;
}
case LINKLIST:
case LINKSET: {
buffer.append(OStringSerializerHelper.COLLECTION_BEGIN);
int items = 0;
// LINKED OBJECTS
for (Object link : (Collection<Object>) iValue) {
if (items++ > 0)
buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
linkToStream(buffer, iRecord, link);
}
buffer.append(OStringSerializerHelper.COLLECTION_END);
break;
}
default:
return OStringSerializerHelper.fieldTypeToString(iType, iValue);
}
return buffer.toString();
}
/**
* Parse a string returning the closer type. To avoid limit exceptions, for integer numbers are returned always LONG and for
* decimal ones always DOUBLE.
*
* @param iUnusualSymbols
* Localized decimal number separators
* @param iValue
* Value to parse
* @return OType.LONG for integers, OType.DOUBLE for decimals and OType.STRING for other
*/
public static OType getNumber(final DecimalFormatSymbols iUnusualSymbols, final String iValue) {
boolean integer = true;
char c;
for (int index = 0; index < iValue.length(); ++index) {
c = iValue.charAt(index);
if (c < '0' || c > '9')
if ((index == 0 && (c == '+' || c == '-')))
continue;
else if (c == iUnusualSymbols.getDecimalSeparator())
integer = false;
else {
return OType.STRING;
}
}
return integer ? OType.LONG : OType.DOUBLE;
}
/**
* Serialize the link.
*
* @param buffer
* @param iParentRecord
* @param iLinked
* Can be an instance of ORID or a Record<?>
*/
private void linkToStream(final StringBuilder buffer, final ORecordSchemaAware<?> iParentRecord, final Object iLinked) {
if (iLinked == null)
// NULL REFERENCE
return;
ORID rid;
buffer.append(OStringSerializerHelper.LINK);
if (iLinked instanceof ORID) {
// JUST THE REFERENCE
rid = (ORID) iLinked;
} else {
// RECORD
ORecordInternal<?> iLinkedRecord = (ORecordInternal<?>) iLinked;
rid = iLinkedRecord.getIdentity();
if (!rid.isValid()) {
// OVERWRITE THE DATABASE TO THE SAME OF PARENT ONE
iLinkedRecord.setDatabase(iParentRecord.getDatabase());
// STORE THE TRAVERSED OBJECT TO KNOW THE RECORD ID. CALL THIS VERSION TO AVOID CLEAR OF STACK IN THREAD-LOCAL
iLinkedRecord.getDatabase().save((ORecordInternal) iLinkedRecord);
}
if (iLinkedRecord instanceof ORecordSchemaAware<?>) {
final ORecordSchemaAware<?> schemaAwareRecord = (ORecordSchemaAware<?>) iLinkedRecord;
if (schemaAwareRecord.getClassName() != null) {
buffer.append(schemaAwareRecord.getClassName());
buffer.append(OStringSerializerHelper.CLASS_SEPARATOR);
}
}
}
if (rid.isValid())
buffer.append(rid.toString());
}
}
| Added tolerance when treats collections with a single value: such as [<value>].
| core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java | Added tolerance when treats collections with a single value: such as [<value>]. | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
<ide> if (iValue.length() == 0)
<ide> return null;
<ide>
<del> // REMOVE BEGIN & END COLLECTIONS CHARACTERS
<del> String value = iValue.substring(1, iValue.length() - 1);
<add> // REMOVE BEGIN & END COLLECTIONS CHARACTERS IF IT'S A COLLECTION
<add> String value = iValue.startsWith("[") ? iValue.substring(1, iValue.length() - 1) : iValue;
<ide>
<ide> Collection<Object> coll = iType == OType.EMBEDDEDLIST ? new ArrayList<Object>() : new HashSet<Object>();
<ide>
<ide> if (iValue.length() == 0)
<ide> return null;
<ide>
<del> // REMOVE BEGIN & END COLLECTIONS CHARACTERS
<del> String value = iValue.substring(1, iValue.length() - 1);
<add> // REMOVE BEGIN & END COLLECTIONS CHARACTERS IF IT'S A COLLECTION
<add> String value = iValue.startsWith("[") ? iValue.substring(1, iValue.length() - 1) : iValue;
<ide>
<ide> Collection<Object> coll = iType == OType.LINKLIST ? new ArrayList<Object>() : new HashSet<Object>();
<ide> |
|
Java | mit | d963885776e45477fd2e28b97d0a0632883451dd | 0 | alwaysallthetime/ADNLib | package com.alwaysallthetime.adnlib;
import android.os.AsyncTask;
import android.os.Build;
import com.alwaysallthetime.adnlib.data.Annotatable;
import com.alwaysallthetime.adnlib.data.Channel;
import com.alwaysallthetime.adnlib.data.File;
import com.alwaysallthetime.adnlib.data.Message;
import com.alwaysallthetime.adnlib.data.Post;
import com.alwaysallthetime.adnlib.data.PrivateMessage;
import com.alwaysallthetime.adnlib.data.StreamMarker;
import com.alwaysallthetime.adnlib.data.StreamMarkerList;
import com.alwaysallthetime.adnlib.data.User;
import com.alwaysallthetime.adnlib.request.AppDotNetApiFileUploadRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiImageUploadRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiJsonRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetOAuthRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetRequest;
import com.alwaysallthetime.adnlib.response.AccessTokenResponseHandler;
import com.alwaysallthetime.adnlib.response.ChannelListResponseHandler;
import com.alwaysallthetime.adnlib.response.ChannelResponseHandler;
import com.alwaysallthetime.adnlib.response.ConfigurationResponseHandler;
import com.alwaysallthetime.adnlib.response.CountResponseHandler;
import com.alwaysallthetime.adnlib.response.FileListResponseHandler;
import com.alwaysallthetime.adnlib.response.FileResponseHandler;
import com.alwaysallthetime.adnlib.response.LoginResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageListResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageResponseHandler;
import com.alwaysallthetime.adnlib.response.PlaceListResponseHandler;
import com.alwaysallthetime.adnlib.response.PlaceResponseHandler;
import com.alwaysallthetime.adnlib.response.PostResponseHandler;
import com.alwaysallthetime.adnlib.response.StreamMarkerListResponseHandler;
import com.alwaysallthetime.adnlib.response.StreamMarkerResponseHandler;
import com.alwaysallthetime.adnlib.response.TokenResponseHandler;
import com.alwaysallthetime.adnlib.response.UserListResponseHandler;
import com.alwaysallthetime.adnlib.response.UserResponseHandler;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.SSLSocketFactory;
public class AppDotNetClient {
public static final String METHOD_DELETE = "DELETE";
public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST";
public static final String METHOD_PUT = "PUT";
protected static final int ID_LENGTH = 10; // max string length of object ID including delimiter
protected static final String ENDPOINT_USERS = "users";
protected static final String ENDPOINT_POSTS = "posts";
protected static final String ENDPOINT_CHANNELS = "channels";
protected static final String ENDPOINT_MESSAGES = "messages";
protected static final String ENDPOINT_PLACES = "places";
protected static final String ENDPOINT_FILES = "files";
protected static final String ENDPOINT_CONFIGURATION = "config";
protected String authHeader;
protected String languageHeader;
protected List<NameValuePair> authParams;
protected SSLSocketFactory sslSocketFactory;
public AppDotNetClient() {
final Locale locale = Locale.getDefault();
languageHeader = String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
public AppDotNetClient(String token) {
this();
setToken(token);
}
public AppDotNetClient(String clientId, String passwordGrantSecret) {
this();
authParams = new ArrayList<NameValuePair>(3);
authParams.add(new BasicNameValuePair("client_id", clientId));
authParams.add(new BasicNameValuePair("password_grant_secret", passwordGrantSecret));
authParams.add(new BasicNameValuePair("grant_type", "password"));
}
public void setToken(String token) {
authHeader = "Bearer " + token;
}
public boolean hasToken() {
return authHeader != null;
}
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
/*
* OAUTH
*/
public void authenticateWithPassword(String username, String password, String scope, LoginResponseHandler responseHandler) {
if (authParams == null)
throw new IllegalStateException("client must be constructed with client ID and password grant secret");
final List<NameValuePair> params = getAuthenticationParams(username, password, scope);
final AccessTokenResponseHandler tokenResponseHandler = new AccessTokenResponseHandler(this, responseHandler);
execute(new AppDotNetOAuthRequest(tokenResponseHandler, params, "access_token"));
}
protected List<NameValuePair> getAuthenticationParams(String username, String password, String scope) {
final List<NameValuePair> params = new ArrayList<NameValuePair>(authParams.size() + 3);
params.addAll(authParams);
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
if (scope != null)
params.add(new BasicNameValuePair("scope", scope));
return params;
}
/*
* USER
*/
public void retrieveUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, userId));
}
public void retrieveUser(String userId, UserResponseHandler responseHandler) {
retrieveUser(userId, null, responseHandler);
}
public void retrieveCurrentUser(QueryParameters queryParameters, UserResponseHandler responseHandler) {
retrieveUser("me", queryParameters, responseHandler);
}
public void retrieveCurrentUser(UserResponseHandler responseHandler) {
retrieveCurrentUser(null, responseHandler);
}
public void updateCurrentUser(User user, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, METHOD_PUT, user, queryParameters, ENDPOINT_USERS, "me"));
}
public void updateCurrentUser(User user, UserResponseHandler responseHandler) {
updateCurrentUser(user, null, responseHandler);
}
public void updateAvatar(byte[] image, int offset, int count, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiImageUploadRequest(responseHandler, "avatar", image, offset, count, queryParameters,
ENDPOINT_USERS, "me/avatar"));
}
public void updateAvatar(byte[] image, int offset, int count, UserResponseHandler responseHandler) {
updateAvatar(image, offset, count, null, responseHandler);
}
public void updateAvatar(byte[] image, QueryParameters queryParameters, UserResponseHandler responseHandler) {
updateAvatar(image, 0, image.length, queryParameters, responseHandler);
}
public void updateAvatar(byte[] image, UserResponseHandler responseHandler) {
updateAvatar(image, null, responseHandler);
}
public void updateCover(byte[] image, int offset, int count, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiImageUploadRequest(responseHandler, "cover", image, offset, count, queryParameters,
ENDPOINT_USERS, "me/cover"));
}
public void updateCover(byte[] image, int offset, int count, UserResponseHandler responseHandler) {
updateCover(image, offset, count, null, responseHandler);
}
public void updateCover(byte[] image, QueryParameters queryParameters, UserResponseHandler responseHandler) {
updateCover(image, 0, image.length, queryParameters, responseHandler);
}
public void updateCover(byte[] image, UserResponseHandler responseHandler) {
updateCover(image, null, responseHandler);
}
public void followUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "follow"));
}
public void followUser(String userId, UserResponseHandler responseHandler) {
followUser(userId, null, responseHandler);
}
public void unfollowUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "follow"));
}
public void unfollowUser(String userId, UserResponseHandler responseHandler) {
unfollowUser(userId, null, responseHandler);
}
public void muteUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "mute"));
}
public void muteUser(String userId, UserResponseHandler responseHandler) {
muteUser(userId, null, responseHandler);
}
public void unmuteUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "mute"));
}
public void unmuteUser(String userId, UserResponseHandler responseHandler) {
unmuteUser(userId, null, responseHandler);
}
public void blockUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "block"));
}
public void blockUser(String userId, UserResponseHandler responseHandler) {
blockUser(userId, null, responseHandler);
}
public void unblockUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "block"));
}
public void unblockUser(String userId, UserResponseHandler responseHandler) {
unblockUser(userId, null, responseHandler);
}
protected void retrieveUsers(String userIds, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", userIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS));
}
public void retrieveUsersById(List<String> userIds, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
retrieveUsers(getIdString(userIds), queryParameters, responseHandler);
}
public void retrieveUsersById(List<String> userIds, UserListResponseHandler responseHandler) {
retrieveUsersById(userIds, null, responseHandler);
}
public void retrieveUsers(List<User> users, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
retrieveUsers(getObjectIdString(users), queryParameters, responseHandler);
}
public void retrieveUsers(List<User> users, UserListResponseHandler responseHandler) {
retrieveUsers(users, null, responseHandler);
}
public void retrieveUsersWithSearchQuery(String query, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("q", query);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "search"));
}
public void retrieveUsersWithSearchQuery(String query, UserListResponseHandler responseHandler) {
retrieveUsersWithSearchQuery(query, null, responseHandler);
}
/*
* POST
*/
public void createPost(Post post, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, post, queryParameters, ENDPOINT_POSTS));
}
public void createPost(Post post, PostResponseHandler responseHandler) {
createPost(post, null, responseHandler);
}
public void retrievePost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_POSTS, postId));
}
public void retrievePost(String postId, PostResponseHandler responseHandler) {
retrievePost(postId, null, responseHandler);
}
public void deletePost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId));
}
public void deletePost(String postId, PostResponseHandler responseHandler) {
deletePost(postId, null, responseHandler);
}
public void repostPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_POSTS, postId, "repost"));
}
public void repostPost(String postId, PostResponseHandler responseHandler) {
repostPost(postId, null, responseHandler);
}
public void unrepostPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId, "repost"));
}
public void unrepostPost(String postId, PostResponseHandler responseHandler) {
unrepostPost(postId, null, responseHandler);
}
public void starPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_POSTS, postId, "star"));
}
public void starPost(String postId, PostResponseHandler responseHandler) {
starPost(postId, null, responseHandler);
}
public void unstarPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId, "star"));
}
public void unstarPost(String postId, PostResponseHandler responseHandler) {
unstarPost(postId, null, responseHandler);
}
/*
* CHANNEL
*/
public void retrieveCurrentUserSubscribedChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS));
}
public void retrieveCurrentUserSubscribedChannels(ChannelListResponseHandler responseHandler) {
retrieveCurrentUserSubscribedChannels(null, responseHandler);
}
public void createChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, channel, queryParameters, ENDPOINT_CHANNELS));
}
public void createChannel(Channel channel, ChannelResponseHandler responseHandler) {
createChannel(channel, null, responseHandler);
}
public void retrieveChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId));
}
public void retrieveChannel(String channelId, ChannelResponseHandler responseHandler) {
retrieveChannel(channelId, null, responseHandler);
}
protected void retrieveChannels(String channelIds, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", channelIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS));
}
public void retrieveChannelsById(List<String> channelIds, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
retrieveChannels(getIdString(channelIds), queryParameters, responseHandler);
}
public void retrieveChannelsById(List<String> channelIds, ChannelListResponseHandler responseHandler) {
retrieveChannelsById(channelIds, null, responseHandler);
}
public void retrieveChannels(List<Channel> channels, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
retrieveChannels(getObjectIdString(channels), queryParameters, responseHandler);
}
public void retrieveChannels(List<Channel> channels, ChannelListResponseHandler responseHandler) {
retrieveChannels(channels, null, responseHandler);
}
public void retrieveChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, "search"));
}
public void retrieveChannelsWithSearchQuery(String query, ChannelListResponseHandler responseHandler) {
retrieveChannelsWithSearchQuery(query, null, responseHandler);
}
public void retrieveChannelsWithSearchQuery(String query, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("q", query);
retrieveChannels(queryParameters, responseHandler);
}
public void retrieveCurrentUserChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_CHANNELS));
}
public void retrieveCurrentUserChannels(ChannelListResponseHandler responseHandler) {
retrieveCurrentUserChannels(null, responseHandler);
}
public void retrieveUnreadPrivateMessageChannelCount(CountResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_USERS, "me", ENDPOINT_CHANNELS, "pm/num_unread"));
}
public void updateChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, METHOD_PUT, channel, queryParameters, ENDPOINT_CHANNELS, channel.getId()));
}
public void updateChannel(Channel channel, ChannelResponseHandler responseHandler) {
updateChannel(channel, null, responseHandler);
}
public void subscribeChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_CHANNELS, channelId, "subscribe"));
}
public void subscribeChannel(String channelId, ChannelResponseHandler responseHandler) {
subscribeChannel(channelId, null, responseHandler);
}
public void subscribeChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
subscribeChannel(channel.getId(), queryParameters, responseHandler);
}
public void subscribeChannel(Channel channel, ChannelResponseHandler responseHandler) {
subscribeChannel(channel, null, responseHandler);
}
public void unsubscribeChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, "subscribe"));
}
public void unsubscribeChannel(String channelId, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channelId, null, responseHandler);
}
public void unsubscribeChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channel.getId(), queryParameters, responseHandler);
}
public void unsubscribeChannel(Channel channel, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channel, null, responseHandler);
}
public void muteChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_CHANNELS, channelId, "mute"));
}
public void muteChannel(String channelId, ChannelResponseHandler responseHandler) {
muteChannel(channelId, null, responseHandler);
}
public void muteChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
muteChannel(channel.getId(), queryParameters, responseHandler);
}
public void muteChannel(Channel channel, ChannelResponseHandler responseHandler) {
muteChannel(channel, null, responseHandler);
}
public void unmuteChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, "mute"));
}
public void unmuteChannel(String channelId, ChannelResponseHandler responseHandler) {
unmuteChannel(channelId, null, responseHandler);
}
public void unmuteChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
unmuteChannel(channel.getId(), queryParameters, responseHandler);
}
public void unmuteChannel(Channel channel, ChannelResponseHandler responseHandler) {
unmuteChannel(channel, null, responseHandler);
}
/*
* MESSAGE
*/
public void retrieveMessagesInChannel(String channelId, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES));
}
public void retrieveMessagesInChannel(String channelId, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channelId, null, responseHandler);
}
public void retrieveMessagesInChannel(Channel channel, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channel.getId(), queryParameters, responseHandler);
}
public void retrieveMessagesInChannel(Channel channel, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channel, null, responseHandler);
}
public void createMessage(String channelId, Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, message, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES));
}
public void createMessage(String channelId, Message message, MessageResponseHandler responseHandler) {
createMessage(channelId, message, null, responseHandler);
}
public void createMessage(Channel channel, Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
createMessage(channel.getId(), message, queryParameters, responseHandler);
}
public void createMessage(Channel channel, Message message, MessageResponseHandler responseHandler) {
createMessage(channel, message, null, responseHandler);
}
public void createPrivateMessage(PrivateMessage message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
if (message.getDestinations() == null)
throw new IllegalArgumentException("private message must specify destinations");
createMessage("pm", message, queryParameters, responseHandler);
}
public void createPrivateMessage(PrivateMessage message, MessageResponseHandler responseHandler) {
createPrivateMessage(message, null, responseHandler);
}
public void retrieveMessage(String channelId, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES, messageId));
}
public void retrieveMessage(String channelId, String messageId, MessageResponseHandler responseHandler) {
retrieveMessage(channelId, messageId, null, responseHandler);
}
public void retrieveMessage(Channel channel, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
retrieveMessage(channel.getId(), messageId, queryParameters, responseHandler);
}
public void retrieveMessage(Channel channel, String messageId, MessageResponseHandler responseHandler) {
retrieveMessage(channel, messageId, null, responseHandler);
}
protected void retrieveMessages(String messageIds, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", messageIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, ENDPOINT_MESSAGES));
}
public void retrieveMessagesById(List<String> messageIds, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessages(getIdString(messageIds), queryParameters, responseHandler);
}
public void retrieveMessagesById(List<String> messageIds, MessageListResponseHandler responseHandler) {
retrieveMessagesById(messageIds, null, responseHandler);
}
public void retrieveMessages(List<Message> messages, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessages(getObjectIdString(messages), queryParameters, responseHandler);
}
public void retrieveMessages(List<Message> messages, MessageListResponseHandler responseHandler) {
retrieveMessages(messages, null, responseHandler);
}
public void retrieveCurrentUserMessages(QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_MESSAGES));
}
public void retrieveCurrentUserMessages(MessageListResponseHandler responseHandler) {
retrieveCurrentUserMessages(null, responseHandler);
}
public void deleteMessage(String channelId, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES, messageId));
}
public void deleteMessage(String channelId, String messageId, MessageResponseHandler responseHandler) {
deleteMessage(channelId, messageId, null, responseHandler);
}
public void deleteMessage(Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
deleteMessage(message.getChannelId(), message.getId(), queryParameters, responseHandler);
}
public void deleteMessage(Message message, MessageResponseHandler responseHandler) {
deleteMessage(message, null, responseHandler);
}
/*
* PLACE
*/
public void retrievePlace(String factualId, PlaceResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_PLACES, factualId));
}
public void retrievePlacesWithSearchQuery(PlaceQueryParameters queryParameters, PlaceListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_PLACES, "search"));
}
/*
* STREAM MARKER
*/
public void updateStreamMarker(StreamMarker streamMarker, StreamMarkerResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, streamMarker, null, ENDPOINT_POSTS, "marker"));
}
public void updateStreamMarkers(StreamMarkerList streamMarkers, StreamMarkerListResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, streamMarkers, null, ENDPOINT_POSTS, "marker"));
}
/*
* FILE
*/
public void retrieveCurrentUserFiles(FileListResponseHandler responseHandler) {
retrieveCurrentUserFiles(null, responseHandler);
}
public void retrieveCurrentUserFiles(QueryParameters queryParameters, FileListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_FILES));
}
public void retrieveFiles(List<File> files, FileListResponseHandler responseHandler) {
retrieveFiles(files, null, responseHandler);
}
public void retrieveFiles(List<File> files, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
retrieveFiles(getObjectIdString(files), queryParameters, responseHandler);
}
public void retrieveFilesById(List<String> fileIds, FileListResponseHandler responseHandler) {
retrieveFilesById(fileIds, null, responseHandler);
}
public void retrieveFilesById(List<String> fileIds, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
retrieveFiles(getIdString(fileIds), queryParameters, responseHandler);
}
protected void retrieveFiles(String fileIds, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", fileIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_FILES));
}
public void createFile(File file, byte[] fileData, String mimeType, FileResponseHandler responseHandler) {
execute(new AppDotNetApiFileUploadRequest(responseHandler, file, fileData, mimeType, ENDPOINT_FILES));
}
public void deleteFile(String fileId, FileResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, null, ENDPOINT_FILES, fileId));
}
/*
* TOKEN
*/
public void retrieveCurrentToken(TokenResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, "token"));
}
/*
* CONFIGURATION
*/
public void retrieveConfiguration(ConfigurationResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_CONFIGURATION));
}
/*
* MISC
*/
protected String getIdString(List<String> ids) {
final StringBuilder buffer = new StringBuilder(ids.size() * ID_LENGTH);
for (final String id : ids) {
buffer.append(id);
buffer.append(',');
}
return buffer.substring(0, buffer.length() - 1);
}
protected String getObjectIdString(List<? extends Annotatable> objects) {
final ArrayList<String> ids = new ArrayList<String>(objects.size());
for (final Annotatable object : objects) {
ids.add(object.getId());
}
return getIdString(ids);
}
protected void execute(AppDotNetRequest request) {
if (request.isAuthenticated() && !hasToken()) {
throw new IllegalStateException("authentication token not set");
}
final AppDotNetClientTask task = new AppDotNetClientTask(authHeader, languageHeader, sslSocketFactory);
// AsyncTask was changed in Honeycomb to execute in serial by default, at which time
// executeOnExecutor was added to specify parallel execution.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, request);
} else {
task.execute(request);
}
}
}
| ADNLibModule/src/main/java/com/alwaysallthetime/adnlib/AppDotNetClient.java | package com.alwaysallthetime.adnlib;
import android.os.AsyncTask;
import android.os.Build;
import com.alwaysallthetime.adnlib.data.Annotatable;
import com.alwaysallthetime.adnlib.data.Channel;
import com.alwaysallthetime.adnlib.data.File;
import com.alwaysallthetime.adnlib.data.Message;
import com.alwaysallthetime.adnlib.data.Post;
import com.alwaysallthetime.adnlib.data.PrivateMessage;
import com.alwaysallthetime.adnlib.data.StreamMarker;
import com.alwaysallthetime.adnlib.data.StreamMarkerList;
import com.alwaysallthetime.adnlib.data.User;
import com.alwaysallthetime.adnlib.request.AppDotNetApiFileUploadRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiImageUploadRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiJsonRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetApiRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetOAuthRequest;
import com.alwaysallthetime.adnlib.request.AppDotNetRequest;
import com.alwaysallthetime.adnlib.response.AccessTokenResponseHandler;
import com.alwaysallthetime.adnlib.response.ChannelListResponseHandler;
import com.alwaysallthetime.adnlib.response.ChannelResponseHandler;
import com.alwaysallthetime.adnlib.response.ConfigurationResponseHandler;
import com.alwaysallthetime.adnlib.response.CountResponseHandler;
import com.alwaysallthetime.adnlib.response.FileListResponseHandler;
import com.alwaysallthetime.adnlib.response.FileResponseHandler;
import com.alwaysallthetime.adnlib.response.LoginResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageListResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageResponseHandler;
import com.alwaysallthetime.adnlib.response.PlaceListResponseHandler;
import com.alwaysallthetime.adnlib.response.PlaceResponseHandler;
import com.alwaysallthetime.adnlib.response.PostResponseHandler;
import com.alwaysallthetime.adnlib.response.StreamMarkerListResponseHandler;
import com.alwaysallthetime.adnlib.response.StreamMarkerResponseHandler;
import com.alwaysallthetime.adnlib.response.TokenResponseHandler;
import com.alwaysallthetime.adnlib.response.UserListResponseHandler;
import com.alwaysallthetime.adnlib.response.UserResponseHandler;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.SSLSocketFactory;
public class AppDotNetClient {
public static final String METHOD_DELETE = "DELETE";
public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST";
public static final String METHOD_PUT = "PUT";
protected static final int ID_LENGTH = 10; // max string length of object ID including delimiter
protected static final String ENDPOINT_USERS = "users";
protected static final String ENDPOINT_POSTS = "posts";
protected static final String ENDPOINT_CHANNELS = "channels";
protected static final String ENDPOINT_MESSAGES = "messages";
protected static final String ENDPOINT_PLACES = "places";
protected static final String ENDPOINT_FILES = "files";
protected static final String ENDPOINT_CONFIGURATION = "config";
protected String authHeader;
protected String languageHeader;
protected List<NameValuePair> authParams;
protected SSLSocketFactory sslSocketFactory;
public AppDotNetClient() {
final Locale locale = Locale.getDefault();
languageHeader = String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
public AppDotNetClient(String token) {
this();
setToken(token);
}
public AppDotNetClient(String clientId, String passwordGrantSecret) {
this();
authParams = new ArrayList<NameValuePair>(3);
authParams.add(new BasicNameValuePair("client_id", clientId));
authParams.add(new BasicNameValuePair("password_grant_secret", passwordGrantSecret));
authParams.add(new BasicNameValuePair("grant_type", "password"));
}
public void setToken(String token) {
authHeader = "Bearer " + token;
}
public boolean hasToken() {
return authHeader != null;
}
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
/*
* OAUTH
*/
public void authenticateWithPassword(String username, String password, String scope, LoginResponseHandler responseHandler) {
if (authParams == null)
throw new IllegalStateException("client must be constructed with client ID and password grant secret");
final List<NameValuePair> params = getAuthenticationParams(username, password, scope);
final AccessTokenResponseHandler tokenResponseHandler = new AccessTokenResponseHandler(this, responseHandler);
execute(new AppDotNetOAuthRequest(tokenResponseHandler, params, "access_token"));
}
protected List<NameValuePair> getAuthenticationParams(String username, String password, String scope) {
final List<NameValuePair> params = new ArrayList<NameValuePair>(authParams.size() + 3);
params.addAll(authParams);
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
if (scope != null)
params.add(new BasicNameValuePair("scope", scope));
return params;
}
/*
* USER
*/
public void retrieveUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, userId));
}
public void retrieveUser(String userId, UserResponseHandler responseHandler) {
retrieveUser(userId, null, responseHandler);
}
public void retrieveCurrentUser(QueryParameters queryParameters, UserResponseHandler responseHandler) {
retrieveUser("me", queryParameters, responseHandler);
}
public void retrieveCurrentUser(UserResponseHandler responseHandler) {
retrieveCurrentUser(null, responseHandler);
}
public void updateCurrentUser(User user, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, METHOD_PUT, user, queryParameters, ENDPOINT_USERS, "me"));
}
public void updateCurrentUser(User user, UserResponseHandler responseHandler) {
updateCurrentUser(user, null, responseHandler);
}
public void updateAvatar(byte[] image, int offset, int count, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiImageUploadRequest(responseHandler, "avatar", image, offset, count, queryParameters,
ENDPOINT_USERS, "me/avatar"));
}
public void updateAvatar(byte[] image, int offset, int count, UserResponseHandler responseHandler) {
updateAvatar(image, offset, count, null, responseHandler);
}
public void updateAvatar(byte[] image, QueryParameters queryParameters, UserResponseHandler responseHandler) {
updateAvatar(image, 0, image.length, queryParameters, responseHandler);
}
public void updateAvatar(byte[] image, UserResponseHandler responseHandler) {
updateAvatar(image, null, responseHandler);
}
public void updateCover(byte[] image, int offset, int count, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiImageUploadRequest(responseHandler, "cover", image, offset, count, queryParameters,
ENDPOINT_USERS, "me/cover"));
}
public void updateCover(byte[] image, int offset, int count, UserResponseHandler responseHandler) {
updateCover(image, offset, count, null, responseHandler);
}
public void updateCover(byte[] image, QueryParameters queryParameters, UserResponseHandler responseHandler) {
updateCover(image, 0, image.length, queryParameters, responseHandler);
}
public void updateCover(byte[] image, UserResponseHandler responseHandler) {
updateCover(image, null, responseHandler);
}
public void followUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "follow"));
}
public void followUser(String userId, UserResponseHandler responseHandler) {
followUser(userId, null, responseHandler);
}
public void unfollowUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "follow"));
}
public void unfollowUser(String userId, UserResponseHandler responseHandler) {
unfollowUser(userId, null, responseHandler);
}
public void muteUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "mute"));
}
public void muteUser(String userId, UserResponseHandler responseHandler) {
muteUser(userId, null, responseHandler);
}
public void unmuteUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "mute"));
}
public void unmuteUser(String userId, UserResponseHandler responseHandler) {
unmuteUser(userId, null, responseHandler);
}
public void blockUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_USERS, userId, "block"));
}
public void blockUser(String userId, UserResponseHandler responseHandler) {
blockUser(userId, null, responseHandler);
}
public void unblockUser(String userId, QueryParameters queryParameters, UserResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_USERS, userId, "block"));
}
public void unblockUser(String userId, UserResponseHandler responseHandler) {
unblockUser(userId, null, responseHandler);
}
protected void retrieveUsers(String userIds, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", userIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS));
}
public void retrieveUsersById(List<String> userIds, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
retrieveUsers(getIdString(userIds), queryParameters, responseHandler);
}
public void retrieveUsersById(List<String> userIds, UserListResponseHandler responseHandler) {
retrieveUsersById(userIds, null, responseHandler);
}
public void retrieveUsers(List<User> users, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
retrieveUsers(getObjectIdString(users), queryParameters, responseHandler);
}
public void retrieveUsers(List<User> users, UserListResponseHandler responseHandler) {
retrieveUsers(users, null, responseHandler);
}
public void retrieveUsersWithSearchQuery(String query, QueryParameters queryParameters, UserListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("q", query);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "search"));
}
public void retrieveUsersWithSearchQuery(String query, UserListResponseHandler responseHandler) {
retrieveUsersWithSearchQuery(query, null, responseHandler);
}
/*
* POST
*/
public void createPost(Post post, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, post, queryParameters, ENDPOINT_POSTS));
}
public void createPost(Post post, PostResponseHandler responseHandler) {
createPost(post, null, responseHandler);
}
public void retrievePost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_POSTS, postId));
}
public void retrievePost(String postId, PostResponseHandler responseHandler) {
retrievePost(postId, null, responseHandler);
}
public void deletePost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId));
}
public void deletePost(String postId, PostResponseHandler responseHandler) {
deletePost(postId, null, responseHandler);
}
public void repostPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_POSTS, postId, "repost"));
}
public void repostPost(String postId, PostResponseHandler responseHandler) {
repostPost(postId, null, responseHandler);
}
public void unrepostPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId, "repost"));
}
public void unrepostPost(String postId, PostResponseHandler responseHandler) {
unrepostPost(postId, null, responseHandler);
}
public void starPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_POSTS, postId, "star"));
}
public void starPost(String postId, PostResponseHandler responseHandler) {
starPost(postId, null, responseHandler);
}
public void unstarPost(String postId, QueryParameters queryParameters, PostResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_POSTS, postId, "star"));
}
public void unstarPost(String postId, PostResponseHandler responseHandler) {
unstarPost(postId, null, responseHandler);
}
/*
* CHANNEL
*/
public void retrieveCurrentUserSubscribedChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS));
}
public void retrieveCurrentUserSubscribedChannels(ChannelListResponseHandler responseHandler) {
retrieveCurrentUserSubscribedChannels(null, responseHandler);
}
public void createChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, channel, queryParameters, ENDPOINT_CHANNELS));
}
public void createChannel(Channel channel, ChannelResponseHandler responseHandler) {
createChannel(channel, null, responseHandler);
}
public void retrieveChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId));
}
public void retrieveChannel(String channelId, ChannelResponseHandler responseHandler) {
retrieveChannel(channelId, null, responseHandler);
}
protected void retrieveChannels(String channelIds, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", channelIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS));
}
public void retrieveChannelsById(List<String> channelIds, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
retrieveChannels(getIdString(channelIds), queryParameters, responseHandler);
}
public void retrieveChannelsById(List<String> channelIds, ChannelListResponseHandler responseHandler) {
retrieveChannelsById(channelIds, null, responseHandler);
}
public void retrieveChannels(List<Channel> channels, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
retrieveChannels(getObjectIdString(channels), queryParameters, responseHandler);
}
public void retrieveChannels(List<Channel> channels, ChannelListResponseHandler responseHandler) {
retrieveChannels(channels, null, responseHandler);
}
public void retrieveChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, "search"));
}
public void retrieveChannelsWithSearchQuery(String query, ChannelListResponseHandler responseHandler) {
retrieveChannelsWithSearchQuery(query, null, responseHandler);
}
public void retrieveChannelsWithSearchQuery(String query, QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("q", query);
retrieveChannels(queryParameters, responseHandler);
}
public void retrieveCurrentUserChannels(QueryParameters queryParameters, ChannelListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_CHANNELS));
}
public void retrieveCurrentUserChannels(ChannelListResponseHandler responseHandler) {
retrieveCurrentUserChannels(null, responseHandler);
}
public void retrieveUnreadPrivateMessageChannelCount(CountResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_USERS, "me", ENDPOINT_CHANNELS, "pm/num_unread"));
}
public void updateChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, METHOD_PUT, channel, queryParameters, ENDPOINT_CHANNELS, channel.getId()));
}
public void updateChannel(Channel channel, ChannelResponseHandler responseHandler) {
updateChannel(channel, null, responseHandler);
}
public void subscribeChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_CHANNELS, channelId, "subscribe"));
}
public void subscribeChannel(String channelId, ChannelResponseHandler responseHandler) {
subscribeChannel(channelId, null, responseHandler);
}
public void subscribeChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
subscribeChannel(channel.getId(), queryParameters, responseHandler);
}
public void subscribeChannel(Channel channel, ChannelResponseHandler responseHandler) {
subscribeChannel(channel, null, responseHandler);
}
public void unsubscribeChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, "subscribe"));
}
public void unsubscribeChannel(String channelId, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channelId, null, responseHandler);
}
public void unsubscribeChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channel.getId(), queryParameters, responseHandler);
}
public void unsubscribeChannel(Channel channel, ChannelResponseHandler responseHandler) {
unsubscribeChannel(channel, null, responseHandler);
}
public void muteChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_POST, queryParameters, ENDPOINT_CHANNELS, channelId, "mute"));
}
public void muteChannel(String channelId, ChannelResponseHandler responseHandler) {
muteChannel(channelId, null, responseHandler);
}
public void muteChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
muteChannel(channel.getId(), queryParameters, responseHandler);
}
public void muteChannel(Channel channel, ChannelResponseHandler responseHandler) {
muteChannel(channel, null, responseHandler);
}
public void unmuteChannel(String channelId, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, "mute"));
}
public void unmuteChannel(String channelId, ChannelResponseHandler responseHandler) {
unmuteChannel(channelId, null, responseHandler);
}
public void unmuteChannel(Channel channel, QueryParameters queryParameters, ChannelResponseHandler responseHandler) {
unmuteChannel(channel.getId(), queryParameters, responseHandler);
}
public void unmuteChannel(Channel channel, ChannelResponseHandler responseHandler) {
unmuteChannel(channel, null, responseHandler);
}
/*
* MESSAGE
*/
public void retrieveMessagesInChannel(String channelId, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES));
}
public void retrieveMessagesInChannel(String channelId, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channelId, null, responseHandler);
}
public void retrieveMessagesInChannel(Channel channel, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channel.getId(), queryParameters, responseHandler);
}
public void retrieveMessagesInChannel(Channel channel, MessageListResponseHandler responseHandler) {
retrieveMessagesInChannel(channel, null, responseHandler);
}
public void createMessage(String channelId, Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, message, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES));
}
public void createMessage(String channelId, Message message, MessageResponseHandler responseHandler) {
createMessage(channelId, message, null, responseHandler);
}
public void createMessage(Channel channel, Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
createMessage(channel.getId(), message, queryParameters, responseHandler);
}
public void createMessage(Channel channel, Message message, MessageResponseHandler responseHandler) {
createMessage(channel, message, null, responseHandler);
}
public void createPrivateMessage(PrivateMessage message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
if (message.getDestinations() == null)
throw new IllegalArgumentException("private message must specify destinations");
createMessage("pm", message, queryParameters, responseHandler);
}
public void createPrivateMessage(PrivateMessage message, MessageResponseHandler responseHandler) {
createPrivateMessage(message, null, responseHandler);
}
public void retrieveMessage(String channelId, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES, messageId));
}
public void retrieveMessage(String channelId, String messageId, MessageResponseHandler responseHandler) {
retrieveMessage(channelId, messageId, null, responseHandler);
}
public void retrieveMessage(Channel channel, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
retrieveMessage(channel.getId(), messageId, queryParameters, responseHandler);
}
public void retrieveMessage(Channel channel, String messageId, MessageResponseHandler responseHandler) {
retrieveMessage(channel, messageId, null, responseHandler);
}
protected void retrieveMessages(String messageIds, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
if (queryParameters == null)
queryParameters = new QueryParameters();
queryParameters.put("ids", messageIds);
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_CHANNELS, ENDPOINT_MESSAGES));
}
public void retrieveMessagesById(List<String> messageIds, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessages(getIdString(messageIds), queryParameters, responseHandler);
}
public void retrieveMessagesById(List<String> messageIds, MessageListResponseHandler responseHandler) {
retrieveMessagesById(messageIds, null, responseHandler);
}
public void retrieveMessages(List<Message> messages, QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
retrieveMessages(getObjectIdString(messages), queryParameters, responseHandler);
}
public void retrieveMessages(List<Message> messages, MessageListResponseHandler responseHandler) {
retrieveMessages(messages, null, responseHandler);
}
public void retrieveCurrentUserMessages(QueryParameters queryParameters, MessageListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_MESSAGES));
}
public void retrieveCurrentUserMessages(MessageListResponseHandler responseHandler) {
retrieveCurrentUserMessages(null, responseHandler);
}
public void deleteMessage(String channelId, String messageId, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, queryParameters, ENDPOINT_CHANNELS, channelId, ENDPOINT_MESSAGES, messageId));
}
public void deleteMessage(String channelId, String messageId, MessageResponseHandler responseHandler) {
deleteMessage(channelId, messageId, null, responseHandler);
}
public void deleteMessage(Message message, QueryParameters queryParameters, MessageResponseHandler responseHandler) {
deleteMessage(message.getChannelId(), message.getId(), queryParameters, responseHandler);
}
public void deleteMessage(Message message, MessageResponseHandler responseHandler) {
deleteMessage(message, null, responseHandler);
}
/*
* PLACE
*/
public void retrievePlace(String factualId, PlaceResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_PLACES, factualId));
}
public void retrievePlacesWithSearchQuery(PlaceQueryParameters queryParameters, PlaceListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_PLACES, "search"));
}
/*
* STREAM MARKER
*/
public void updateStreamMarker(StreamMarker streamMarker, StreamMarkerResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, streamMarker, null, ENDPOINT_POSTS, "marker"));
}
public void updateStreamMarkers(StreamMarkerList streamMarkers, StreamMarkerListResponseHandler responseHandler) {
execute(new AppDotNetApiJsonRequest(responseHandler, streamMarkers, null, ENDPOINT_POSTS, "marker"));
}
/*
* FILE
*/
public void retrieveCurrentUserFiles(FileListResponseHandler responseHandler) {
retrieveCurrentUserFiles(null, responseHandler);
}
public void retrieveCurrentUserFiles(QueryParameters queryParameters, FileListResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_FILES));
}
public void createFile(File file, byte[] fileData, String mimeType, FileResponseHandler responseHandler) {
execute(new AppDotNetApiFileUploadRequest(responseHandler, file, fileData, mimeType, ENDPOINT_FILES));
}
public void deleteFile(String fileId, FileResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, METHOD_DELETE, null, ENDPOINT_FILES, fileId));
}
/*
* TOKEN
*/
public void retrieveCurrentToken(TokenResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, "token"));
}
/*
* CONFIGURATION
*/
public void retrieveConfiguration(ConfigurationResponseHandler responseHandler) {
execute(new AppDotNetApiRequest(responseHandler, null, ENDPOINT_CONFIGURATION));
}
/*
* MISC
*/
protected String getIdString(List<String> ids) {
final StringBuilder buffer = new StringBuilder(ids.size() * ID_LENGTH);
for (final String id : ids) {
buffer.append(id);
buffer.append(',');
}
return buffer.substring(0, buffer.length() - 1);
}
protected String getObjectIdString(List<? extends Annotatable> objects) {
final ArrayList<String> ids = new ArrayList<String>(objects.size());
for (final Annotatable object : objects) {
ids.add(object.getId());
}
return getIdString(ids);
}
protected void execute(AppDotNetRequest request) {
if (request.isAuthenticated() && !hasToken()) {
throw new IllegalStateException("authentication token not set");
}
final AppDotNetClientTask task = new AppDotNetClientTask(authHeader, languageHeader, sslSocketFactory);
// AsyncTask was changed in Honeycomb to execute in serial by default, at which time
// executeOnExecutor was added to specify parallel execution.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, request);
} else {
task.execute(request);
}
}
}
| add methods for batch file retrievals
| ADNLibModule/src/main/java/com/alwaysallthetime/adnlib/AppDotNetClient.java | add methods for batch file retrievals | <ide><path>DNLibModule/src/main/java/com/alwaysallthetime/adnlib/AppDotNetClient.java
<ide> execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_USERS, "me", ENDPOINT_FILES));
<ide> }
<ide>
<add> public void retrieveFiles(List<File> files, FileListResponseHandler responseHandler) {
<add> retrieveFiles(files, null, responseHandler);
<add> }
<add>
<add> public void retrieveFiles(List<File> files, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
<add> retrieveFiles(getObjectIdString(files), queryParameters, responseHandler);
<add> }
<add>
<add> public void retrieveFilesById(List<String> fileIds, FileListResponseHandler responseHandler) {
<add> retrieveFilesById(fileIds, null, responseHandler);
<add> }
<add>
<add> public void retrieveFilesById(List<String> fileIds, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
<add> retrieveFiles(getIdString(fileIds), queryParameters, responseHandler);
<add> }
<add>
<add> protected void retrieveFiles(String fileIds, QueryParameters queryParameters, FileListResponseHandler responseHandler) {
<add> if (queryParameters == null)
<add> queryParameters = new QueryParameters();
<add>
<add> queryParameters.put("ids", fileIds);
<add> execute(new AppDotNetApiRequest(responseHandler, queryParameters, ENDPOINT_FILES));
<add> }
<add>
<ide> public void createFile(File file, byte[] fileData, String mimeType, FileResponseHandler responseHandler) {
<ide> execute(new AppDotNetApiFileUploadRequest(responseHandler, file, fileData, mimeType, ENDPOINT_FILES));
<ide> } |
|
Java | lgpl-2.1 | error: pathspec 'xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/RootHandler.java' did not match any file(s) known to git
| 309054fb335400bd42a09b2fb2cc04d2402b5d60 | 1 | xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.extension.xar.internal.handler.packager.xml;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xwiki.component.manager.ComponentManager;
/**
*
* @version $Id$
* @since 4.0M1
*/
public class RootHandler extends AbstractHandler
{
private Map<String, ContentHandler> handlers = new HashMap<String, ContentHandler>();
public RootHandler(ComponentManager componentManager)
{
super(componentManager, null);
}
public void setHandler(String element, ContentHandler handler)
{
this.handlers.put(element, handler);
}
@Override
protected void startHandlerElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
ContentHandler handler = this.handlers.get(qName);
if (handler != null) {
setCurrentHandler(handler);
} else {
throw new UnknownRootElement(qName);
}
}
}
| xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/RootHandler.java | Put back class removed by mistake
| xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/RootHandler.java | Put back class removed by mistake | <ide><path>wiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/RootHandler.java
<add>/*
<add> * See the NOTICE file distributed with this work for additional
<add> * information regarding copyright ownership.
<add> *
<add> * This is free software; you can redistribute it and/or modify it
<add> * under the terms of the GNU Lesser General Public License as
<add> * published by the Free Software Foundation; either version 2.1 of
<add> * the License, or (at your option) any later version.
<add> *
<add> * This software is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add> * Lesser General Public License for more details.
<add> *
<add> * You should have received a copy of the GNU Lesser General Public
<add> * License along with this software; if not, write to the Free
<add> * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
<add> * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
<add> */
<add>package org.xwiki.extension.xar.internal.handler.packager.xml;
<add>
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>
<add>import org.xml.sax.Attributes;
<add>import org.xml.sax.ContentHandler;
<add>import org.xml.sax.SAXException;
<add>import org.xwiki.component.manager.ComponentManager;
<add>
<add>/**
<add> *
<add> * @version $Id$
<add> * @since 4.0M1
<add> */
<add>public class RootHandler extends AbstractHandler
<add>{
<add> private Map<String, ContentHandler> handlers = new HashMap<String, ContentHandler>();
<add>
<add> public RootHandler(ComponentManager componentManager)
<add> {
<add> super(componentManager, null);
<add> }
<add>
<add> public void setHandler(String element, ContentHandler handler)
<add> {
<add> this.handlers.put(element, handler);
<add> }
<add>
<add> @Override
<add> protected void startHandlerElement(String uri, String localName, String qName, Attributes attributes)
<add> throws SAXException
<add> {
<add> ContentHandler handler = this.handlers.get(qName);
<add>
<add> if (handler != null) {
<add> setCurrentHandler(handler);
<add> } else {
<add> throw new UnknownRootElement(qName);
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 84252575933c4b1bad2b3b5f5cd5f38199ee36cc | 0 | gfyoung/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,s1monw/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,rajanm/elasticsearch,coding0011/elasticsearch,kalimatas/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,gfyoung/elasticsearch,rajanm/elasticsearch,GlenRSmith/elasticsearch,uschindler/elasticsearch,s1monw/elasticsearch,HonzaKral/elasticsearch,kalimatas/elasticsearch,robin13/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,rajanm/elasticsearch,s1monw/elasticsearch,scorpionvicky/elasticsearch,kalimatas/elasticsearch,scorpionvicky/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,rajanm/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch,s1monw/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,rajanm/elasticsearch,GlenRSmith/elasticsearch,HonzaKral/elasticsearch,kalimatas/elasticsearch,HonzaKral/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,kalimatas/elasticsearch,rajanm/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch,s1monw/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.get;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.util.Collections;
import java.util.function.Predicate;
import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
import static org.elasticsearch.index.get.GetResultTests.copyGetResult;
import static org.elasticsearch.index.get.GetResultTests.mutateGetResult;
import static org.elasticsearch.index.get.GetResultTests.randomGetResult;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.elasticsearch.test.XContentTestUtils.insertRandomFields;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
public class GetResponseTests extends ESTestCase {
public void testToAndFromXContent() throws Exception {
doFromXContentTestWithRandomFields(false);
}
/**
* This test adds random fields and objects to the xContent rendered out to
* ensure we can parse it back to be forward compatible with additions to
* the xContent
*/
public void testFromXContentWithRandomFields() throws IOException {
doFromXContentTestWithRandomFields(true);
}
private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException {
XContentType xContentType = randomFrom(XContentType.values());
Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
GetResponse getResponse = new GetResponse(tuple.v1());
GetResponse expectedGetResponse = new GetResponse(tuple.v2());
boolean humanReadable = randomBoolean();
BytesReference originalBytes = toShuffledXContent(getResponse, xContentType, ToXContent.EMPTY_PARAMS, humanReadable, "_source");
BytesReference mutated;
if (addRandomFields) {
// "_source" and "fields" just consists of key/value pairs, we shouldn't add anything random there. It is already
// randomized in the randomGetResult() method anyway. Also, we cannot add anything in the root object since this is
// where GetResult's metadata fields are rendered out while // other fields are rendered out in a "fields" object.
Predicate<String> excludeFilter = (s) -> s.isEmpty() || s.contains("fields") || s.contains("_source");
mutated = insertRandomFields(xContentType, originalBytes, excludeFilter, random());
} else {
mutated = originalBytes;
}
GetResponse parsedGetResponse;
try (XContentParser parser = createParser(xContentType.xContent(), mutated)) {
parsedGetResponse = GetResponse.fromXContent(parser);
assertNull(parser.nextToken());
}
assertEquals(expectedGetResponse.getSourceAsMap(), parsedGetResponse.getSourceAsMap());
//print the parsed object out and test that the output is the same as the original output
BytesReference finalBytes = toXContent(parsedGetResponse, xContentType, humanReadable);
assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
//check that the source stays unchanged, no shuffling of keys nor anything like that
assertEquals(expectedGetResponse.getSourceAsString(), parsedGetResponse.getSourceAsString());
}
public void testToXContent() {
{
GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " +
"\"value1\", \"field2\":\"value2\"}"), Collections.singletonMap("field1", new DocumentField("field1",
Collections.singletonList("value1")))));
String output = Strings.toString(getResponse);
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" " +
": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", output);
}
{
GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, false, null, null));
String output = Strings.toString(getResponse);
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"found\":false}", output);
}
}
public void testToString() {
GetResponse getResponse = new GetResponse(
new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " + "\"value1\", \"field2\":\"value2\"}"),
Collections.singletonMap("field1", new DocumentField("field1", Collections.singletonList("value1")))));
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" "
+ ": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", getResponse.toString());
}
public void testEqualsAndHashcode() {
checkEqualsAndHashCode(new GetResponse(randomGetResult(XContentType.JSON).v1()), GetResponseTests::copyGetResponse,
GetResponseTests::mutateGetResponse);
}
public void testFromXContentThrowsParsingException() throws IOException {
GetResponse getResponse = new GetResponse(new GetResult(null, null, null, randomIntBetween(1, 5), randomBoolean(), null, null));
XContentType xContentType = randomFrom(XContentType.values());
BytesReference originalBytes = toShuffledXContent(getResponse, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean());
try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
ParsingException exception = expectThrows(ParsingException.class, () -> GetResponse.fromXContent(parser));
assertEquals("Missing required fields [_index,_type,_id]", exception.getMessage());
}
}
private static GetResponse copyGetResponse(GetResponse getResponse) {
return new GetResponse(copyGetResult(getResponse.getResult));
}
private static GetResponse mutateGetResponse(GetResponse getResponse) {
return new GetResponse(mutateGetResult(getResponse.getResult));
}
}
| server/src/test/java/org/elasticsearch/action/get/GetResponseTests.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.get;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.util.Collections;
import java.util.function.Predicate;
import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
import static org.elasticsearch.index.get.GetResultTests.copyGetResult;
import static org.elasticsearch.index.get.GetResultTests.mutateGetResult;
import static org.elasticsearch.index.get.GetResultTests.randomGetResult;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.elasticsearch.test.XContentTestUtils.insertRandomFields;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
public class GetResponseTests extends ESTestCase {
public void testToAndFromXContent() throws Exception {
doFromXContentTestWithRandomFields(false);
}
/**
* This test adds random fields and objects to the xContent rendered out to
* ensure we can parse it back to be forward compatible with additions to
* the xContent
*/
public void testFromXContentWithRandomFields() throws IOException {
doFromXContentTestWithRandomFields(true);
}
private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException {
XContentType xContentType = randomFrom(XContentType.values());
Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
GetResponse getResponse = new GetResponse(tuple.v1());
GetResponse expectedGetResponse = new GetResponse(tuple.v2());
boolean humanReadable = randomBoolean();
BytesReference originalBytes = toShuffledXContent(getResponse, xContentType, ToXContent.EMPTY_PARAMS, humanReadable, "_source");
BytesReference mutated;
if (addRandomFields) {
// "_source" and "fields" just consists of key/value pairs, we shouldn't add anything random there. It is already
// randomized in the randomGetResult() method anyway. Also, we cannot add anything in the root object since this is
// where GetResult's metadata fields are rendered out while // other fields are rendered out in a "fields" object.
Predicate<String> excludeFilter = (s) -> s.isEmpty() || s.contains("fields") || s.contains("_source");
mutated = insertRandomFields(xContentType, originalBytes, excludeFilter, random());
} else {
mutated = originalBytes;
}
GetResponse parsedGetResponse;
try (XContentParser parser = createParser(xContentType.xContent(), mutated)) {
parsedGetResponse = GetResponse.fromXContent(parser);
assertNull(parser.nextToken());
}
assertEquals(expectedGetResponse, parsedGetResponse);
//print the parsed object out and test that the output is the same as the original output
BytesReference finalBytes = toXContent(parsedGetResponse, xContentType, humanReadable);
assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
//check that the source stays unchanged, no shuffling of keys nor anything like that
assertEquals(expectedGetResponse.getSourceAsString(), parsedGetResponse.getSourceAsString());
}
public void testToXContent() {
{
GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " +
"\"value1\", \"field2\":\"value2\"}"), Collections.singletonMap("field1", new DocumentField("field1",
Collections.singletonList("value1")))));
String output = Strings.toString(getResponse);
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" " +
": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", output);
}
{
GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, false, null, null));
String output = Strings.toString(getResponse);
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"found\":false}", output);
}
}
public void testToString() {
GetResponse getResponse = new GetResponse(
new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " + "\"value1\", \"field2\":\"value2\"}"),
Collections.singletonMap("field1", new DocumentField("field1", Collections.singletonList("value1")))));
assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" "
+ ": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", getResponse.toString());
}
public void testEqualsAndHashcode() {
checkEqualsAndHashCode(new GetResponse(randomGetResult(XContentType.JSON).v1()), GetResponseTests::copyGetResponse,
GetResponseTests::mutateGetResponse);
}
public void testFromXContentThrowsParsingException() throws IOException {
GetResponse getResponse = new GetResponse(new GetResult(null, null, null, randomIntBetween(1, 5), randomBoolean(), null, null));
XContentType xContentType = randomFrom(XContentType.values());
BytesReference originalBytes = toShuffledXContent(getResponse, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean());
try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
ParsingException exception = expectThrows(ParsingException.class, () -> GetResponse.fromXContent(parser));
assertEquals("Missing required fields [_index,_type,_id]", exception.getMessage());
}
}
private static GetResponse copyGetResponse(GetResponse getResponse) {
return new GetResponse(copyGetResult(getResponse.getResult));
}
private static GetResponse mutateGetResponse(GetResponse getResponse) {
return new GetResponse(mutateGetResult(getResponse.getResult));
}
}
| [TEST] Fix issue parsing response out of order
When parsing GetResponse it was possible that the equality check failed because
items in the map were in a different order (in the `.equals` implementation).
| server/src/test/java/org/elasticsearch/action/get/GetResponseTests.java | [TEST] Fix issue parsing response out of order | <ide><path>erver/src/test/java/org/elasticsearch/action/get/GetResponseTests.java
<ide> parsedGetResponse = GetResponse.fromXContent(parser);
<ide> assertNull(parser.nextToken());
<ide> }
<del> assertEquals(expectedGetResponse, parsedGetResponse);
<add> assertEquals(expectedGetResponse.getSourceAsMap(), parsedGetResponse.getSourceAsMap());
<ide> //print the parsed object out and test that the output is the same as the original output
<ide> BytesReference finalBytes = toXContent(parsedGetResponse, xContentType, humanReadable);
<ide> assertToXContentEquivalent(originalBytes, finalBytes, xContentType); |
|
Java | apache-2.0 | 43cdfd44e45a95a9a2d642cc3045349a682bcddd | 0 | ZionTech/pac4j,robgratz/pac4j,jacklotusho/pac4j,mmoayyed/pac4j,yangzilong1986/pac4j,JacobASeverson/pac4j,ganquan0910/pac4j,izerui/pac4j,CRDNicolasBourbaki/pac4j,ganquan0910/pac4j,leleuj/pac4j,JacobASeverson/pac4j,robgratz/pac4j,topicusonderwijs/pac4j,mmoayyed/pac4j,liuzhg/pac4j,zawn/pac4j,ZionTech/pac4j,zawn/pac4j,Kevin2030/pac4j,jacklotusho/pac4j,Kevin2030/pac4j,milinda/pac4j,jayaramsankara/pac4j,topicusonderwijs/pac4j,liuzhg/pac4j,izerui/pac4j,thesamet/pac4j,yangzilong1986/pac4j,thesamet/pac4j,jayaramsankara/pac4j,garpinc/pac4j,jkacer/pac4j,pac4j/pac4j,pac4j/pac4j,garpinc/pac4j,CRDNicolasBourbaki/pac4j,jkacer/pac4j | /*
Copyright 2012 - 2013 Jerome Leleu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.pac4j.oauth.profile.converter;
import java.lang.reflect.Constructor;
import org.pac4j.core.profile.converter.AttributeConverter;
import org.pac4j.oauth.profile.XmlObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class converts a XML into a XML object.
*
* @author Jerome Leleu
* @since 1.4.1
*/
public final class XmlObjectConverter implements AttributeConverter<XmlObject> {
private static final Logger logger = LoggerFactory.getLogger(XmlObjectConverter.class);
private final Class<? extends XmlObject> clazz;
public XmlObjectConverter(final Class<? extends XmlObject> clazz) {
this.clazz = clazz;
}
public XmlObject convert(final Object attribute) {
if (attribute != null && attribute instanceof String) {
try {
final Constructor<? extends XmlObject> constructor = this.clazz.getDeclaredConstructor();
final XmlObject xmlObject = constructor.newInstance();
xmlObject.buildFrom((String) attribute);
return xmlObject;
} catch (final Exception e) {
logger.error("Cannot build XmlObject : {}", e, this.clazz);
}
}
return null;
}
}
| pac4j-oauth/src/main/java/org/pac4j/oauth/profile/converter/XmlObjectConverter.java | /*
Copyright 2012 - 2013 Jerome Leleu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.pac4j.oauth.profile.converter;
import java.lang.reflect.Constructor;
import org.pac4j.core.profile.converter.AttributeConverter;
import org.pac4j.oauth.profile.XmlObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class converts a XML into a XML object.
*
* @author Jerome Leleu
* @since 1.4.2
*/
public final class XmlObjectConverter implements AttributeConverter<XmlObject> {
private static final Logger logger = LoggerFactory.getLogger(XmlObjectConverter.class);
private final Class<? extends XmlObject> clazz;
public XmlObjectConverter(final Class<? extends XmlObject> clazz) {
this.clazz = clazz;
}
public XmlObject convert(final Object attribute) {
if (attribute != null && attribute instanceof String) {
try {
final Constructor<? extends XmlObject> constructor = this.clazz.getDeclaredConstructor();
final XmlObject xmlObject = constructor.newInstance();
xmlObject.buildFrom((String) attribute);
return xmlObject;
} catch (final Exception e) {
logger.error("Cannot build XmlObject : {}", e, this.clazz);
}
}
return null;
}
}
| fix Javadco
| pac4j-oauth/src/main/java/org/pac4j/oauth/profile/converter/XmlObjectConverter.java | fix Javadco | <ide><path>ac4j-oauth/src/main/java/org/pac4j/oauth/profile/converter/XmlObjectConverter.java
<ide> * This class converts a XML into a XML object.
<ide> *
<ide> * @author Jerome Leleu
<del> * @since 1.4.2
<add> * @since 1.4.1
<ide> */
<ide> public final class XmlObjectConverter implements AttributeConverter<XmlObject> {
<ide> |
|
JavaScript | mit | 2ff9df11c27237c8f622d3b43848d60977e537c9 | 0 | cjewett-hiya/qwest,cjewett-hiya/qwest,pyrsmk/qwest,cjewett-hiya/qwest,pyrsmk/qwest,pyrsmk/qwest | /*! qwest 2.2.1 (https://github.com/pyrsmk/qwest) */
module.exports = function() {
var global = window || this,
pinkyswear = require('pinkyswear'),
jparam = require('jquery-param'),
// Default response type for XDR in auto mode
defaultXdrResponseType = 'json',
// Variables for limit mechanism
limit = null,
requests = 0,
request_stack = [],
// Get XMLHttpRequest object
getXHR = function(){
return global.XMLHttpRequest?
new global.XMLHttpRequest():
new ActiveXObject('Microsoft.XMLHTTP');
},
// Guess XHR version
xhr2 = (getXHR().responseType===''),
// Core function
qwest = function(method, url, data, options, before) {
// Format
method = method.toUpperCase();
data = data || null;
options = options || {};
// Define variables
var nativeResponseParsing = false,
crossOrigin,
xhr,
xdr = false,
timeoutInterval,
aborted = false,
attempts = 0,
headers = {},
mimeTypes = {
text: '*/*',
xml: 'text/xml',
json: 'application/json',
post: 'application/x-www-form-urlencoded'
},
accept = {
text: '*/*',
xml: 'application/xml; q=1.0, text/xml; q=0.8, */*; q=0.1',
json: 'application/json; q=1.0, text/*; q=0.8, */*; q=0.1'
},
vars = '',
i, j,
serialized,
response,
sending = false,
delayed = false,
timeout_start,
// Create the promise
promise = pinkyswear(function(pinky) {
pinky['catch'] = function(f) {
return pinky.then(null, f);
};
pinky.complete = function(f) {
return pinky.then(f, f);
};
// Override
if('pinkyswear' in options) {
for(i in options.pinkyswear) {
pinky[i] = options.pinkyswear[i];
}
}
pinky.send = function() {
// Prevent further send() calls
if(sending) {
return;
}
// Reached request limit, get out!
if(requests == limit) {
request_stack.push(pinky);
return;
}
++requests;
sending = true;
// Start the chrono
timeout_start = new Date().getTime();
// Get XHR object
xhr = getXHR();
if(crossOrigin) {
if(!('withCredentials' in xhr) && global.XDomainRequest) {
xhr = new XDomainRequest(); // CORS with IE8/9
xdr = true;
if(method!='GET' && method!='POST') {
method = 'POST';
}
}
}
// Open connection
if(xdr) {
xhr.open(method, url);
}
else {
xhr.open(method, url, options.async, options.user, options.password);
if(xhr2 && options.async) {
xhr.withCredentials = options.withCredentials;
}
}
// Set headers
if(!xdr) {
for(var i in headers) {
if(headers[i]) {
xhr.setRequestHeader(i, headers[i]);
}
}
}
// Verify if the response type is supported by the current browser
if(xhr2 && options.responseType!='document' && options.responseType!='auto') { // Don't verify for 'document' since we're using an internal routine
try {
xhr.responseType = options.responseType;
nativeResponseParsing = (xhr.responseType==options.responseType);
}
catch(e){}
}
// Plug response handler
if(xhr2 || xdr) {
xhr.onload = handleResponse;
xhr.onerror = handleError;
}
else {
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
handleResponse();
}
};
}
// Override mime type to ensure the response is well parsed
if(options.responseType!='auto' && 'overrideMimeType' in xhr) {
xhr.overrideMimeType(mimeTypes[options.responseType]);
}
// Run 'before' callback
if(before) {
before(xhr);
}
// Send request
if(xdr) {
setTimeout(function(){ // https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest
xhr.send(method!='GET'?data:null);
},0);
}
else {
xhr.send(method!='GET'?data:null);
}
};
return pinky;
}),
// Handle the response
handleResponse = function() {
// Prepare
var i, responseType;
--requests;
sending = false;
// Verify timeout state
// --- https://stackoverflow.com/questions/7287706/ie-9-javascript-error-c00c023f
if(new Date().getTime()-timeout_start >= options.timeout) {
if(!options.attempts || ++attempts!=options.attempts) {
promise.send();
}
else {
promise(false, [xhr,response,new Error('Timeout ('+url+')')]);
}
return;
}
// Launch next stacked request
if(request_stack.length) {
request_stack.shift().send();
}
// Handle response
try{
// Process response
if(nativeResponseParsing && 'response' in xhr && xhr.response!==null) {
response = xhr.response;
}
else if(options.responseType == 'document') {
var frame = document.createElement('iframe');
frame.style.display = 'none';
document.body.appendChild(frame);
frame.contentDocument.open();
frame.contentDocument.write(xhr.response);
frame.contentDocument.close();
response = frame.contentDocument;
document.body.removeChild(frame);
}
else{
// Guess response type
responseType = options.responseType;
if(responseType == 'auto') {
if(xdr) {
responseType = defaultXdrResponseType;
}
else {
var ct = xhr.getResponseHeader('Content-Type') || '';
if(ct.indexOf(mimeTypes.json)>-1) {
responseType = 'json';
}
else if(ct.indexOf(mimeTypes.xml)>-1) {
responseType = 'xml';
}
else {
responseType = 'text';
}
}
}
// Handle response type
switch(responseType) {
case 'json':
try {
if('JSON' in global) {
response = JSON.parse(xhr.responseText);
}
else {
response = eval('('+xhr.responseText+')');
}
}
catch(e) {
throw "Error while parsing JSON body : "+e;
}
break;
case 'xml':
// Based on jQuery's parseXML() function
try {
// Standard
if(global.DOMParser) {
response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml');
}
// IE<9
else {
response = new ActiveXObject('Microsoft.XMLDOM');
response.async = 'false';
response.loadXML(xhr.responseText);
}
}
catch(e) {
response = undefined;
}
if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) {
throw 'Invalid XML';
}
break;
default:
response = xhr.responseText;
}
}
// Late status code verification to allow passing data when, per example, a 409 is returned
// --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if('status' in xhr && !/^2|1223/.test(xhr.status)) {
throw xhr.status+' ('+xhr.statusText+')';
}
// Fulfilled
promise(true, [xhr,response]);
}
catch(e) {
// Rejected
promise(false, [xhr,response,e]);
}
},
// Handle errors
handleError = function(e) {
--requests;
promise(false, [xhr,null,new Error('Connection aborted')]);
};
// Normalize options
options.async = 'async' in options?!!options.async:true;
options.cache = 'cache' in options?!!options.cache:false;
options.dataType = 'dataType' in options?options.dataType.toLowerCase():'post';
options.responseType = 'responseType' in options?options.responseType.toLowerCase():'auto';
options.user = options.user || '';
options.password = options.password || '';
options.withCredentials = !!options.withCredentials;
options.timeout = 'timeout' in options?parseInt(options.timeout,10):30000;
options.attempts = 'attempts' in options?parseInt(options.attempts,10):1;
// Guess if we're dealing with a cross-origin request
i = url.match(/\/\/(.+?)\//);
crossOrigin = i && (i[1]?i[1]!=location.host:false);
// Prepare data
if('ArrayBuffer' in global && data instanceof ArrayBuffer) {
options.dataType = 'arraybuffer';
}
else if('Blob' in global && data instanceof Blob) {
options.dataType = 'blob';
}
else if('Document' in global && data instanceof Document) {
options.dataType = 'document';
}
else if('FormData' in global && data instanceof FormData) {
options.dataType = 'formdata';
}
switch(options.dataType) {
case 'json':
data = JSON.stringify(data);
break;
case 'post':
data = jparam(data);
}
// Prepare headers
if(options.headers) {
var format = function(match,p1,p2) {
return p1 + p2.toUpperCase();
};
for(i in options.headers) {
headers[i.replace(/(^|-)([^-])/g,format)] = options.headers[i];
}
}
if(!('Content-Type' in headers) && method!='GET') {
if(options.dataType in mimeTypes) {
if(mimeTypes[options.dataType]) {
headers['Content-Type'] = mimeTypes[options.dataType];
}
}
}
if(!headers.Accept) {
headers.Accept = (options.responseType in accept)?accept[options.responseType]:'*/*';
}
if(!crossOrigin && !('X-Requested-With' in headers)) { // (that header breaks in legacy browsers with CORS)
headers['X-Requested-With'] = 'XMLHttpRequest';
}
if(!options.cache && !('Cache-Control' in headers)) {
headers['Cache-Control'] = 'no-cache';
}
// Prepare URL
if(method=='GET' && data) {
vars += data;
}
if(vars) {
url += (/\?/.test(url)?'&':'?')+vars;
}
// Start the request
if(options.async) {
promise.send();
}
// Return promise
return promise;
};
// Return the external qwest object
return {
base: '',
get: function(url, data, options, before) {
return qwest('GET', this.base+url, data, options, before);
},
post: function(url, data, options, before) {
return qwest('POST', this.base+url, data, options, before);
},
put: function(url, data, options, before) {
return qwest('PUT', this.base+url, data, options, before);
},
'delete': function(url, data, options, before) {
return qwest('DELETE', this.base+url, data, options, before);
},
map: function(type, url, data, options, before) {
return qwest(type.toUpperCase(), this.base+url, data, options, before);
},
xhr2: xhr2,
// obsolete
limit: function(by) {
limit = by;
},
// obsolete
setDefaultXdrResponseType: function(type) {
defaultXdrResponseType = type.toLowerCase();
}
};
}();
| src/qwest.js | /*! qwest 2.2.1 (https://github.com/pyrsmk/qwest) */
module.exports = function() {
var global = window,
pinkyswear = require('pinkyswear'),
jparam = require('jquery-param'),
// Default response type for XDR in auto mode
defaultXdrResponseType = 'json',
// Variables for limit mechanism
limit = null,
requests = 0,
request_stack = [],
// Get XMLHttpRequest object
getXHR = function(){
return global.XMLHttpRequest?
new global.XMLHttpRequest():
new ActiveXObject('Microsoft.XMLHTTP');
},
// Guess XHR version
xhr2 = (getXHR().responseType===''),
// Core function
qwest = function(method, url, data, options, before) {
// Format
method = method.toUpperCase();
data = data || null;
options = options || {};
// Define variables
var nativeResponseParsing = false,
crossOrigin,
xhr,
xdr = false,
timeoutInterval,
aborted = false,
attempts = 0,
headers = {},
mimeTypes = {
text: '*/*',
xml: 'text/xml',
json: 'application/json',
post: 'application/x-www-form-urlencoded'
},
accept = {
text: '*/*',
xml: 'application/xml; q=1.0, text/xml; q=0.8, */*; q=0.1',
json: 'application/json; q=1.0, text/*; q=0.8, */*; q=0.1'
},
vars = '',
i, j,
serialized,
response,
sending = false,
delayed = false,
timeout_start,
// Create the promise
promise = pinkyswear(function(pinky) {
pinky['catch'] = function(f) {
return pinky.then(null, f);
};
pinky.complete = function(f) {
return pinky.then(f, f);
};
// Override
if('pinkyswear' in options) {
for(i in options.pinkyswear) {
pinky[i] = options.pinkyswear[i];
}
}
pinky.send = function() {
// Prevent further send() calls
if(sending) {
return;
}
// Reached request limit, get out!
if(requests == limit) {
request_stack.push(pinky);
return;
}
++requests;
sending = true;
// Start the chrono
timeout_start = new Date().getTime();
// Get XHR object
xhr = getXHR();
if(crossOrigin) {
if(!('withCredentials' in xhr) && global.XDomainRequest) {
xhr = new XDomainRequest(); // CORS with IE8/9
xdr = true;
if(method!='GET' && method!='POST') {
method = 'POST';
}
}
}
// Open connection
if(xdr) {
xhr.open(method, url);
}
else {
xhr.open(method, url, options.async, options.user, options.password);
if(xhr2 && options.async) {
xhr.withCredentials = options.withCredentials;
}
}
// Set headers
if(!xdr) {
for(var i in headers) {
if(headers[i]) {
xhr.setRequestHeader(i, headers[i]);
}
}
}
// Verify if the response type is supported by the current browser
if(xhr2 && options.responseType!='document' && options.responseType!='auto') { // Don't verify for 'document' since we're using an internal routine
try {
xhr.responseType = options.responseType;
nativeResponseParsing = (xhr.responseType==options.responseType);
}
catch(e){}
}
// Plug response handler
if(xhr2 || xdr) {
xhr.onload = handleResponse;
xhr.onerror = handleError;
}
else {
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
handleResponse();
}
};
}
// Override mime type to ensure the response is well parsed
if(options.responseType!='auto' && 'overrideMimeType' in xhr) {
xhr.overrideMimeType(mimeTypes[options.responseType]);
}
// Run 'before' callback
if(before) {
before(xhr);
}
// Send request
if(xdr) {
setTimeout(function(){ // https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest
xhr.send(method!='GET'?data:null);
},0);
}
else {
xhr.send(method!='GET'?data:null);
}
};
return pinky;
}),
// Handle the response
handleResponse = function() {
// Prepare
var i, responseType;
--requests;
sending = false;
// Verify timeout state
// --- https://stackoverflow.com/questions/7287706/ie-9-javascript-error-c00c023f
if(new Date().getTime()-timeout_start >= options.timeout) {
if(!options.attempts || ++attempts!=options.attempts) {
promise.send();
}
else {
promise(false, [xhr,response,new Error('Timeout ('+url+')')]);
}
return;
}
// Launch next stacked request
if(request_stack.length) {
request_stack.shift().send();
}
// Handle response
try{
// Process response
if(nativeResponseParsing && 'response' in xhr && xhr.response!==null) {
response = xhr.response;
}
else if(options.responseType == 'document') {
var frame = document.createElement('iframe');
frame.style.display = 'none';
document.body.appendChild(frame);
frame.contentDocument.open();
frame.contentDocument.write(xhr.response);
frame.contentDocument.close();
response = frame.contentDocument;
document.body.removeChild(frame);
}
else{
// Guess response type
responseType = options.responseType;
if(responseType == 'auto') {
if(xdr) {
responseType = defaultXdrResponseType;
}
else {
var ct = xhr.getResponseHeader('Content-Type') || '';
if(ct.indexOf(mimeTypes.json)>-1) {
responseType = 'json';
}
else if(ct.indexOf(mimeTypes.xml)>-1) {
responseType = 'xml';
}
else {
responseType = 'text';
}
}
}
// Handle response type
switch(responseType) {
case 'json':
try {
if('JSON' in global) {
response = JSON.parse(xhr.responseText);
}
else {
response = eval('('+xhr.responseText+')');
}
}
catch(e) {
throw "Error while parsing JSON body : "+e;
}
break;
case 'xml':
// Based on jQuery's parseXML() function
try {
// Standard
if(global.DOMParser) {
response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml');
}
// IE<9
else {
response = new ActiveXObject('Microsoft.XMLDOM');
response.async = 'false';
response.loadXML(xhr.responseText);
}
}
catch(e) {
response = undefined;
}
if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) {
throw 'Invalid XML';
}
break;
default:
response = xhr.responseText;
}
}
// Late status code verification to allow passing data when, per example, a 409 is returned
// --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if('status' in xhr && !/^2|1223/.test(xhr.status)) {
throw xhr.status+' ('+xhr.statusText+')';
}
// Fulfilled
promise(true, [xhr,response]);
}
catch(e) {
// Rejected
promise(false, [xhr,response,e]);
}
},
// Handle errors
handleError = function(e) {
--requests;
promise(false, [xhr,null,new Error('Connection aborted')]);
};
// Normalize options
options.async = 'async' in options?!!options.async:true;
options.cache = 'cache' in options?!!options.cache:false;
options.dataType = 'dataType' in options?options.dataType.toLowerCase():'post';
options.responseType = 'responseType' in options?options.responseType.toLowerCase():'auto';
options.user = options.user || '';
options.password = options.password || '';
options.withCredentials = !!options.withCredentials;
options.timeout = 'timeout' in options?parseInt(options.timeout,10):30000;
options.attempts = 'attempts' in options?parseInt(options.attempts,10):1;
// Guess if we're dealing with a cross-origin request
i = url.match(/\/\/(.+?)\//);
crossOrigin = i && (i[1]?i[1]!=location.host:false);
// Prepare data
if('ArrayBuffer' in global && data instanceof ArrayBuffer) {
options.dataType = 'arraybuffer';
}
else if('Blob' in global && data instanceof Blob) {
options.dataType = 'blob';
}
else if('Document' in global && data instanceof Document) {
options.dataType = 'document';
}
else if('FormData' in global && data instanceof FormData) {
options.dataType = 'formdata';
}
switch(options.dataType) {
case 'json':
data = JSON.stringify(data);
break;
case 'post':
data = jparam(data);
}
// Prepare headers
if(options.headers) {
var format = function(match,p1,p2) {
return p1 + p2.toUpperCase();
};
for(i in options.headers) {
headers[i.replace(/(^|-)([^-])/g,format)] = options.headers[i];
}
}
if(!('Content-Type' in headers) && method!='GET') {
if(options.dataType in mimeTypes) {
if(mimeTypes[options.dataType]) {
headers['Content-Type'] = mimeTypes[options.dataType];
}
}
}
if(!headers.Accept) {
headers.Accept = (options.responseType in accept)?accept[options.responseType]:'*/*';
}
if(!crossOrigin && !('X-Requested-With' in headers)) { // (that header breaks in legacy browsers with CORS)
headers['X-Requested-With'] = 'XMLHttpRequest';
}
if(!options.cache && !('Cache-Control' in headers)) {
headers['Cache-Control'] = 'no-cache';
}
// Prepare URL
if(method=='GET' && data) {
vars += data;
}
if(vars) {
url += (/\?/.test(url)?'&':'?')+vars;
}
// Start the request
if(options.async) {
promise.send();
}
// Return promise
return promise;
};
// Return the external qwest object
return {
base: '',
get: function(url, data, options, before) {
return qwest('GET', this.base+url, data, options, before);
},
post: function(url, data, options, before) {
return qwest('POST', this.base+url, data, options, before);
},
put: function(url, data, options, before) {
return qwest('PUT', this.base+url, data, options, before);
},
'delete': function(url, data, options, before) {
return qwest('DELETE', this.base+url, data, options, before);
},
map: function(type, url, data, options, before) {
return qwest(type.toUpperCase(), this.base+url, data, options, before);
},
xhr2: xhr2,
// obsolete
limit: function(by) {
limit = by;
},
// obsolete
setDefaultXdrResponseType: function(type) {
defaultXdrResponseType = type.toLowerCase();
}
};
}();
| Update qwest.js | src/qwest.js | Update qwest.js | <ide><path>rc/qwest.js
<ide>
<ide> module.exports = function() {
<ide>
<del> var global = window,
<add> var global = window || this,
<ide> pinkyswear = require('pinkyswear'),
<ide> jparam = require('jquery-param'),
<ide> // Default response type for XDR in auto mode |
|
Java | apache-2.0 | a69d08848dda9a07eee667c1f9373c67b0bb7b4e | 0 | AndroidLearnerchn/AndroidLibraryProject | /*
* Copyright (c) 2013 by CDAC Chennai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @File CAFService
* @Created: 20.07.2014
* @author: Prasenjit
* Last Change: 24.07.2014 by Prasenjit
*/
package com.contextawareframework.backgroundservices;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class CAFService extends Service{
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Tag for debugging */
private final String TAG = "CAFService";
private static boolean enableDebugging = false;
/**
* Method to start debugging, all log tags in this class will be printed
*/
protected void setEnableDebugging(boolean value)
{
enableDebugging = value;
}
/**
* Method to stop debugging.
*/
protected boolean getEnableDebugging()
{
return enableDebugging;
}
/** Called when the service is being created. */
@Override
public void onCreate() {
if(enableDebugging)
Log.d(TAG,"onCreate");
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(enableDebugging)
Log.d(TAG,"onStartCommand");
return mStartMode;
}
/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onBind");
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onUnbind");
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onRebind");
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
if(enableDebugging)
Log.d(TAG,"onDestroy");
}
}
| ContextAwareFramework/src/com/contextawareframework/backgroundservices/CAFService.java | /*
* Copyright (c) 2013 by CDAC Chennai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.contextawareframework.backgroundservices;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class CAFService extends Service{
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Tag for debugging */
private final String TAG = "CAFService";
private static boolean enableDebugging = false;
/**
* Method to start debugging, all log tags in this class will be printed
*/
protected void setEnableDebugging(boolean value)
{
enableDebugging = value;
}
protected boolean getEnableDebugging()
{
return enableDebugging;
}
/** Called when the service is being created. */
@Override
public void onCreate() {
if(enableDebugging)
Log.d(TAG,"onCreate");
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(enableDebugging)
Log.d(TAG,"onStartCommand");
return mStartMode;
}
/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onBind");
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onUnbind");
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
if(enableDebugging)
Log.d(TAG,"onRebind");
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
if(enableDebugging)
Log.d(TAG,"onDestroy");
}
}
| Proper Commenting | ContextAwareFramework/src/com/contextawareframework/backgroundservices/CAFService.java | Proper Commenting | <ide><path>ontextAwareFramework/src/com/contextawareframework/backgroundservices/CAFService.java
<ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<add> *
<add> * @File CAFService
<add> * @Created: 20.07.2014
<add> * @author: Prasenjit
<add> * Last Change: 24.07.2014 by Prasenjit
<ide> */
<ide> package com.contextawareframework.backgroundservices;
<ide>
<ide> public class CAFService extends Service{
<ide>
<ide> /** indicates how to behave if the service is killed */
<del> int mStartMode;
<del> /** interface for clients that bind */
<del> IBinder mBinder;
<del> /** indicates whether onRebind should be used */
<del> boolean mAllowRebind;
<del> /** Tag for debugging */
<del> private final String TAG = "CAFService";
<del> private static boolean enableDebugging = false;
<del>
<del> /**
<del> * Method to start debugging, all log tags in this class will be printed
<del> */
<del> protected void setEnableDebugging(boolean value)
<del> {
<del> enableDebugging = value;
<del> }
<del> protected boolean getEnableDebugging()
<del> {
<del> return enableDebugging;
<del> }
<del> /** Called when the service is being created. */
<del> @Override
<del> public void onCreate() {
<del> if(enableDebugging)
<del> Log.d(TAG,"onCreate");
<del> }
<add> int mStartMode;
<ide>
<del> /** The service is starting, due to a call to startService() */
<del> @Override
<del> public int onStartCommand(Intent intent, int flags, int startId) {
<del> if(enableDebugging)
<del> Log.d(TAG,"onStartCommand");
<del> return mStartMode;
<del> }
<add> /** interface for clients that bind */
<add> IBinder mBinder;
<ide>
<del> /** A client is binding to the service with bindService() */
<del> @Override
<del> public IBinder onBind(Intent intent) {
<del> if(enableDebugging)
<del> Log.d(TAG,"onBind");
<del> return mBinder;
<del> }
<add> /** indicates whether onRebind should be used */
<add> boolean mAllowRebind;
<ide>
<del> /** Called when all clients have unbound with unbindService() */
<del> @Override
<del> public boolean onUnbind(Intent intent) {
<del> if(enableDebugging)
<del> Log.d(TAG,"onUnbind");
<del> return mAllowRebind;
<del> }
<add> /** Tag for debugging */
<add> private final String TAG = "CAFService";
<add> private static boolean enableDebugging = false;
<ide>
<del> /** Called when a client is binding to the service with bindService()*/
<del> @Override
<del> public void onRebind(Intent intent) {
<del> if(enableDebugging)
<del> Log.d(TAG,"onRebind");
<del> }
<add> /**
<add> * Method to start debugging, all log tags in this class will be printed
<add> */
<add> protected void setEnableDebugging(boolean value)
<add> {
<add> enableDebugging = value;
<add> }
<add> /**
<add> * Method to stop debugging.
<add> */
<add> protected boolean getEnableDebugging()
<add> {
<add> return enableDebugging;
<add> }
<add> /** Called when the service is being created. */
<add> @Override
<add> public void onCreate() {
<add> if(enableDebugging)
<add> Log.d(TAG,"onCreate");
<add> }
<ide>
<del> /** Called when The service is no longer used and is being destroyed */
<del> @Override
<del> public void onDestroy() {
<del> if(enableDebugging)
<del> Log.d(TAG,"onDestroy");
<del> }
<del>
<add> /** The service is starting, due to a call to startService() */
<add> @Override
<add> public int onStartCommand(Intent intent, int flags, int startId) {
<add> if(enableDebugging)
<add> Log.d(TAG,"onStartCommand");
<add> return mStartMode;
<add> }
<add>
<add> /** A client is binding to the service with bindService() */
<add> @Override
<add> public IBinder onBind(Intent intent) {
<add> if(enableDebugging)
<add> Log.d(TAG,"onBind");
<add> return mBinder;
<add> }
<add>
<add> /** Called when all clients have unbound with unbindService() */
<add> @Override
<add> public boolean onUnbind(Intent intent) {
<add> if(enableDebugging)
<add> Log.d(TAG,"onUnbind");
<add> return mAllowRebind;
<add> }
<add>
<add> /** Called when a client is binding to the service with bindService()*/
<add> @Override
<add> public void onRebind(Intent intent) {
<add> if(enableDebugging)
<add> Log.d(TAG,"onRebind");
<add> }
<add>
<add> /** Called when The service is no longer used and is being destroyed */
<add> @Override
<add> public void onDestroy() {
<add> if(enableDebugging)
<add> Log.d(TAG,"onDestroy");
<add> }
<add>
<ide> } |
|
Java | mit | 8532d388f89cd103ca1c86dff192f5242c6c27c3 | 0 | MylesIsCool/ViaVersion | package us.myles.ViaVersion.protocols.protocol1_9to1_8.storage;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.boss.BossBar;
import us.myles.ViaVersion.api.boss.BossColor;
import us.myles.ViaVersion.api.boss.BossStyle;
import us.myles.ViaVersion.api.data.StoredObject;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_10Types;
import us.myles.ViaVersion.api.minecraft.Position;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;
import us.myles.ViaVersion.api.minecraft.metadata.types.MetaType1_9;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.api.type.types.version.Types1_9;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.chat.GameMode;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.metadata.MetadataRewriter;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.providers.BossBarProvider;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.providers.EntityIdProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Getter
public class EntityTracker extends StoredObject {
private final Map<Integer, UUID> uuidMap = new ConcurrentHashMap<>();
private final Map<Integer, Entity1_10Types.EntityType> clientEntityTypes = new ConcurrentHashMap<>();
private final Map<Integer, List<Metadata>> metadataBuffer = new ConcurrentHashMap<>();
private final Map<Integer, Integer> vehicleMap = new ConcurrentHashMap<>();
private final Map<Integer, BossBar> bossBarMap = new ConcurrentHashMap<>();
private final Set<Integer> validBlocking = Sets.newConcurrentHashSet();
private final Set<Integer> knownHolograms = Sets.newConcurrentHashSet();
private final Cache<Position, Integer> blockInteractions = CacheBuilder.newBuilder().maximumSize(10).expireAfterAccess(250, TimeUnit.MILLISECONDS).build();
@Setter
private boolean blocking = false;
@Setter
private boolean autoTeam = false;
@Setter
private int entityID = -1;
@Setter
private Position currentlyDigging = null;
private boolean teamExists = false;
@Setter
private GameMode gameMode;
@Setter
private int mainHand;
public EntityTracker(UserConnection user) {
super(user);
}
public UUID getEntityUUID(int id) {
UUID uuid = uuidMap.get(id);
if (uuid == null) {
uuid = UUID.randomUUID();
uuidMap.put(id, uuid);
}
return uuid;
}
public void setSecondHand(Item item) {
setSecondHand(entityID, item);
}
public void setSecondHand(int entityID, Item item) {
PacketWrapper wrapper = new PacketWrapper(0x3C, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Type.VAR_INT, 1); // slot
wrapper.write(Type.ITEM, item);
try {
wrapper.send(Protocol1_9TO1_8.class);
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeEntity(Integer entityID) {
clientEntityTypes.remove(entityID);
vehicleMap.remove(entityID);
uuidMap.remove(entityID);
validBlocking.remove(entityID);
knownHolograms.remove(entityID);
metadataBuffer.remove(entityID);
BossBar bar = bossBarMap.remove(entityID);
if (bar != null) {
bar.hide();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleRemove(getUser(), bar.getId());
}
}
public boolean interactedBlockRecently(int x, int y, int z) {
if (blockInteractions.size() == 0)
return false;
for (Position p : blockInteractions.asMap().keySet()) {
if (p.getX() == x)
if (p.getY() == y)
if (p.getZ() == z)
return true;
}
return false;
}
public void addBlockInteraction(Position p) {
blockInteractions.put(p, 0);
}
public void handleMetadata(int entityID, List<Metadata> metadataList) {
Entity1_10Types.EntityType type = clientEntityTypes.get(entityID);
if (type == null) {
return;
}
for (Metadata metadata : new ArrayList<>(metadataList)) {
// Fix: wither (crash fix)
if (type == Entity1_10Types.EntityType.WITHER) {
if (metadata.getId() == 10) {
metadataList.remove(metadata);
//metadataList.add(new Metadata(10, NewType.Byte.getTypeID(), Type.BYTE, 0));
}
}
// Fix: enderdragon (crash fix)
if (type == Entity1_10Types.EntityType.ENDER_DRAGON) {
if (metadata.getId() == 11) {
metadataList.remove(metadata);
// metadataList.add(new Metadata(11, NewType.Byte.getTypeID(), Type.VAR_INT, 0));
}
}
if (type == Entity1_10Types.EntityType.SKELETON) {
if ((getMetaByIndex(metadataList, 12)) == null) {
metadataList.add(new Metadata(12, MetaType1_9.Boolean, true));
}
}
//ECHOPET Patch
if (type == Entity1_10Types.EntityType.HORSE) {
// Wrong metadata value from EchoPet, patch since it's discontinued. (https://github.com/DSH105/EchoPet/blob/06947a8b08ce40be9a518c2982af494b3b99d140/modules/API/src/main/java/com/dsh105/echopet/compat/api/entity/HorseArmour.java#L22)
if (metadata.getId() == 16 && (int) metadata.getValue() == Integer.MIN_VALUE)
metadata.setValue(0);
}
if (type == Entity1_10Types.EntityType.PLAYER) {
if (metadata.getId() == 0) {
// Byte
byte data = (byte) metadata.getValue();
if (entityID != getProvidedEntityId() && Via.getConfig().isShieldBlocking()) {
if ((data & 0x10) == 0x10) {
if (validBlocking.contains(entityID)) {
Item shield = new Item((short) 442, (byte) 1, (short) 0, null);
setSecondHand(entityID, shield);
} else {
setSecondHand(entityID, null);
}
} else {
setSecondHand(entityID, null);
}
}
}
}
if (type == Entity1_10Types.EntityType.ARMOR_STAND && Via.getConfig().isHologramPatch()) {
if (metadata.getId() == 0 && getMetaByIndex(metadataList, 10) != null) {
Metadata meta = getMetaByIndex(metadataList, 10); //Only happens if the armorstand is small
byte data = (byte) metadata.getValue();
// Check invisible | Check small | Check if custom name is empty | Check if custom name visible is true
if ((data & 0x20) == 0x20 && ((byte) meta.getValue() & 0x01) == 0x01
&& ((String) getMetaByIndex(metadataList, 2).getValue()).length() != 0 && (boolean) getMetaByIndex(metadataList, 3).getValue()) {
if (!knownHolograms.contains(entityID)) {
knownHolograms.add(entityID);
try {
// Send movement
PacketWrapper wrapper = new PacketWrapper(0x25, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Type.SHORT, (short) 0);
wrapper.write(Type.SHORT, (short) (128D * (Via.getConfig().getHologramYOffset() * 32D)));
wrapper.write(Type.SHORT, (short) 0);
wrapper.write(Type.BOOLEAN, true);
wrapper.send(Protocol1_9TO1_8.class, true, false);
} catch (Exception ignored) {
}
}
}
}
}
UUID uuid = getUser().get(ProtocolInfo.class).getUuid();
// Boss bar
if (Via.getConfig().isBossbarPatch()) {
if (type == Entity1_10Types.EntityType.ENDER_DRAGON || type == Entity1_10Types.EntityType.WITHER) {
if (metadata.getId() == 2) {
BossBar bar = bossBarMap.get(entityID);
String title = (String) metadata.getValue();
title = title.isEmpty() ? (type == Entity1_10Types.EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither") : title;
if (bar == null) {
bar = Via.getAPI().createBossBar(title, BossColor.PINK, BossStyle.SOLID);
bossBarMap.put(entityID, bar);
bar.addPlayer(uuid);
bar.show();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleAdd(getUser(), bar.getId());
} else {
bar.setTitle(title);
}
} else if (metadata.getId() == 6 && !Via.getConfig().isBossbarAntiflicker()) { // If anti flicker is enabled, don't update health
BossBar bar = bossBarMap.get(entityID);
// Make health range between 0 and 1
float maxHealth = type == Entity1_10Types.EntityType.ENDER_DRAGON ? 200.0f : 300.0f;
float health = Math.max(0.0f, Math.min(((float) metadata.getValue()) / maxHealth, 1.0f));
if (bar == null) {
String title = type == Entity1_10Types.EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither";
bar = Via.getAPI().createBossBar(title, health, BossColor.PINK, BossStyle.SOLID);
bossBarMap.put(entityID, bar);
bar.addPlayer(uuid);
bar.show();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleAdd(getUser(), bar.getId());
} else {
bar.setHealth(health);
}
}
}
}
}
}
public Metadata getMetaByIndex(List<Metadata> list, int index) {
for (Metadata meta : list)
if (index == meta.getId())
return meta;
return null;
}
public void sendTeamPacket(boolean add, boolean now) {
PacketWrapper wrapper = new PacketWrapper(0x41, null, getUser());
wrapper.write(Type.STRING, "viaversion"); // Use viaversion as name
if (add) {
// add
if (!teamExists) {
wrapper.write(Type.BYTE, (byte) 0); // make team
wrapper.write(Type.STRING, "viaversion");
wrapper.write(Type.STRING, ""); // prefix
wrapper.write(Type.STRING, ""); // suffix
wrapper.write(Type.BYTE, (byte) 0); // friendly fire
wrapper.write(Type.STRING, ""); // nametags
wrapper.write(Type.STRING, "never"); // collision rule :)
wrapper.write(Type.BYTE, (byte) 0); // color
} else {
wrapper.write(Type.BYTE, (byte) 3);
}
wrapper.write(Type.STRING_ARRAY, new String[] {getUser().get(ProtocolInfo.class).getUsername()});
} else {
wrapper.write(Type.BYTE, (byte) 1); // remove team
}
teamExists = add;
try {
wrapper.send(Protocol1_9TO1_8.class, true, now);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addMetadataToBuffer(int entityID, List<Metadata> metadataList) {
final List<Metadata> metadata = metadataBuffer.get(entityID);
if (metadata != null) {
metadata.addAll(metadataList);
} else {
metadataBuffer.put(entityID, metadataList);
}
}
public void sendMetadataBuffer(int entityID) {
List<Metadata> metadataList = metadataBuffer.get(entityID);
if (metadataList != null) {
PacketWrapper wrapper = new PacketWrapper(0x39, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Types1_9.METADATA_LIST, metadataList);
MetadataRewriter.transform(getClientEntityTypes().get(entityID), metadataList);
handleMetadata(entityID, metadataList);
if (metadataList.size() > 0) {
try {
wrapper.send(Protocol1_9TO1_8.class);
} catch (Exception e) {
e.printStackTrace();
}
}
metadataBuffer.remove(entityID);
}
}
public int getProvidedEntityId() {
try {
return Via.getManager().getProviders().get(EntityIdProvider.class).getEntityId(getUser());
} catch (Exception e) {
return entityID;
}
}
}
| common/src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/storage/EntityTracker.java | package us.myles.ViaVersion.protocols.protocol1_9to1_8.storage;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.boss.BossBar;
import us.myles.ViaVersion.api.boss.BossColor;
import us.myles.ViaVersion.api.boss.BossStyle;
import us.myles.ViaVersion.api.data.StoredObject;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.entities.Entity1_10Types;
import us.myles.ViaVersion.api.minecraft.Position;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.minecraft.metadata.Metadata;
import us.myles.ViaVersion.api.minecraft.metadata.types.MetaType1_9;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.api.type.types.version.Types1_9;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.chat.GameMode;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.metadata.MetadataRewriter;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.providers.BossBarProvider;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.providers.EntityIdProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Getter
public class EntityTracker extends StoredObject {
private final Map<Integer, UUID> uuidMap = new ConcurrentHashMap<>();
private final Map<Integer, Entity1_10Types.EntityType> clientEntityTypes = new ConcurrentHashMap<>();
private final Map<Integer, List<Metadata>> metadataBuffer = new ConcurrentHashMap<>();
private final Map<Integer, Integer> vehicleMap = new ConcurrentHashMap<>();
private final Map<Integer, BossBar> bossBarMap = new ConcurrentHashMap<>();
private final Set<Integer> validBlocking = Sets.newConcurrentHashSet();
private final Set<Integer> knownHolograms = Sets.newConcurrentHashSet();
private final Cache<Position, Integer> blockInteractions = CacheBuilder.newBuilder().maximumSize(10).expireAfterAccess(250, TimeUnit.MILLISECONDS).build();
@Setter
private boolean blocking = false;
@Setter
private boolean autoTeam = false;
@Setter
private int entityID = -1;
@Setter
private Position currentlyDigging = null;
private boolean teamExists = false;
@Setter
private GameMode gameMode;
@Setter
private int mainHand;
public EntityTracker(UserConnection user) {
super(user);
}
public UUID getEntityUUID(int id) {
UUID uuid = uuidMap.get(id);
if (uuid == null) {
uuid = UUID.randomUUID();
uuidMap.put(id, uuid);
}
return uuid;
}
public void setSecondHand(Item item) {
setSecondHand(entityID, item);
}
public void setSecondHand(int entityID, Item item) {
PacketWrapper wrapper = new PacketWrapper(0x3C, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Type.VAR_INT, 1); // slot
wrapper.write(Type.ITEM, item);
try {
wrapper.send(Protocol1_9TO1_8.class);
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeEntity(Integer entityID) {
clientEntityTypes.remove(entityID);
vehicleMap.remove(entityID);
uuidMap.remove(entityID);
validBlocking.remove(entityID);
knownHolograms.remove(entityID);
metadataBuffer.remove(entityID);
BossBar bar = bossBarMap.remove(entityID);
if (bar != null) {
bar.hide();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleRemove(getUser(), bar.getId());
}
}
public boolean interactedBlockRecently(int x, int y, int z) {
if (blockInteractions.size() == 0)
return false;
for (Position p : blockInteractions.asMap().keySet()) {
if (p.getX() == x)
if (p.getY() == y)
if (p.getZ() == z)
return true;
}
return false;
}
public void addBlockInteraction(Position p) {
blockInteractions.put(p, 0);
}
public void handleMetadata(int entityID, List<Metadata> metadataList) {
Entity1_10Types.EntityType type = clientEntityTypes.get(entityID);
if (type == null) {
return;
}
for (Metadata metadata : new ArrayList<>(metadataList)) {
// Fix: wither (crash fix)
if (type == Entity1_10Types.EntityType.WITHER) {
if (metadata.getId() == 10) {
metadataList.remove(metadata);
//metadataList.add(new Metadata(10, NewType.Byte.getTypeID(), Type.BYTE, 0));
}
}
// Fix: enderdragon (crash fix)
if (type == Entity1_10Types.EntityType.ENDER_DRAGON) {
if (metadata.getId() == 11) {
metadataList.remove(metadata);
// metadataList.add(new Metadata(11, NewType.Byte.getTypeID(), Type.VAR_INT, 0));
}
}
if (type == Entity1_10Types.EntityType.SKELETON) {
if ((getMetaByIndex(metadataList, 12)) == null) {
metadataList.add(new Metadata(12, MetaType1_9.Boolean, true));
}
}
//ECHOPET Patch
if (type == Entity1_10Types.EntityType.HORSE) {
// Wrong metadata value from EchoPet, patch since it's discontinued. (https://github.com/DSH105/EchoPet/blob/06947a8b08ce40be9a518c2982af494b3b99d140/modules/API/src/main/java/com/dsh105/echopet/compat/api/entity/HorseArmour.java#L22)
if (metadata.getId() == 16 && (int) metadata.getValue() == Integer.MIN_VALUE)
metadata.setValue(0);
}
if (type == Entity1_10Types.EntityType.PLAYER) {
if (metadata.getId() == 0) {
// Byte
byte data = (byte) metadata.getValue();
if (entityID != getProvidedEntityId() && Via.getConfig().isShieldBlocking()) {
if ((data & 0x10) == 0x10) {
if (validBlocking.contains(entityID)) {
Item shield = new Item((short) 442, (byte) 1, (short) 0, null);
setSecondHand(entityID, shield);
} else {
setSecondHand(entityID, null);
}
} else {
setSecondHand(entityID, null);
}
}
}
}
if (type == Entity1_10Types.EntityType.ARMOR_STAND && Via.getConfig().isHologramPatch()) {
if (metadata.getId() == 0 && getMetaByIndex(metadataList, 10) != null) {
Metadata meta = getMetaByIndex(metadataList, 10); //Only happens if the armorstand is small
byte data = (byte) metadata.getValue();
// Check invisible | Check small | Check if custom name is empty | Check if custom name visible is true
if ((data & 0x20) == 0x20 && ((byte) meta.getValue() & 0x01) == 0x01
&& ((String) getMetaByIndex(metadataList, 2).getValue()).length() != 0 && (boolean) getMetaByIndex(metadataList, 3).getValue()) {
if (!knownHolograms.contains(entityID)) {
knownHolograms.add(entityID);
try {
// Send movement
PacketWrapper wrapper = new PacketWrapper(0x25, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Type.SHORT, (short) 0);
wrapper.write(Type.SHORT, (short) (128D * (Via.getConfig().getHologramYOffset() * 32D)));
wrapper.write(Type.SHORT, (short) 0);
wrapper.write(Type.BOOLEAN, true);
wrapper.send(Protocol1_9TO1_8.class, true, false);
} catch (Exception ignored) {
}
}
}
}
}
UUID uuid = getUser().get(ProtocolInfo.class).getUuid();
// Boss bar
if (Via.getConfig().isBossbarPatch()) {
if (type == Entity1_10Types.EntityType.ENDER_DRAGON || type == Entity1_10Types.EntityType.WITHER) {
if (metadata.getId() == 2) {
BossBar bar = bossBarMap.get(entityID);
String title = (String) metadata.getValue();
title = title.isEmpty() ? (type == Entity1_10Types.EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither") : title;
if (bar == null) {
bar = Via.getAPI().createBossBar(title, BossColor.PINK, BossStyle.SOLID);
bossBarMap.put(entityID, bar);
bar.addPlayer(uuid);
bar.show();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleAdd(getUser(), bar.getId());
} else {
bar.setTitle(title);
}
} else if (metadata.getId() == 6 && !Via.getConfig().isBossbarAntiflicker()) { // If anti flicker is enabled, don't update health
BossBar bar = bossBarMap.get(entityID);
// Make health range between 0 and 1
float maxHealth = type == Entity1_10Types.EntityType.ENDER_DRAGON ? 200.0f : 300.0f;
float health = Math.max(0.0f, Math.min(((float) metadata.getValue()) / maxHealth, 1.0f));
if (bar == null) {
String title = type == Entity1_10Types.EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither";
bar = Via.getAPI().createBossBar(title, health, BossColor.PINK, BossStyle.SOLID);
bossBarMap.put(entityID, bar);
bar.addPlayer(uuid);
bar.show();
// Send to provider
Via.getManager().getProviders().get(BossBarProvider.class).handleAdd(getUser(), bar.getId());
} else {
bar.setHealth(health);
}
}
}
}
}
}
public Metadata getMetaByIndex(List<Metadata> list, int index) {
for (Metadata meta : list)
if (index == meta.getId())
return meta;
return null;
}
public void sendTeamPacket(boolean add, boolean now) {
PacketWrapper wrapper = new PacketWrapper(0x41, null, getUser());
wrapper.write(Type.STRING, "viaversion"); // Use viaversion as name
if (add) {
// add
if (!teamExists) {
wrapper.write(Type.BYTE, (byte) 0); // make team
wrapper.write(Type.STRING, "viaversion");
wrapper.write(Type.STRING, ""); // prefix
wrapper.write(Type.STRING, ""); // suffix
wrapper.write(Type.BYTE, (byte) 0); // friendly fire
wrapper.write(Type.STRING, ""); // nametags
wrapper.write(Type.STRING, "never"); // collision rule :)
wrapper.write(Type.BYTE, (byte) 0); // color
} else {
wrapper.write(Type.BYTE, (byte) 3);
}
wrapper.write(Type.VAR_INT, 1); // player count
wrapper.write(Type.STRING, getUser().get(ProtocolInfo.class).getUsername());
} else {
wrapper.write(Type.BYTE, (byte) 1); // remove team
}
teamExists = add;
try {
wrapper.send(Protocol1_9TO1_8.class, true, now);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addMetadataToBuffer(int entityID, List<Metadata> metadataList) {
final List<Metadata> metadata = metadataBuffer.get(entityID);
if (metadata != null) {
metadata.addAll(metadataList);
} else {
metadataBuffer.put(entityID, metadataList);
}
}
public void sendMetadataBuffer(int entityID) {
List<Metadata> metadataList = metadataBuffer.get(entityID);
if (metadataList != null) {
PacketWrapper wrapper = new PacketWrapper(0x39, null, getUser());
wrapper.write(Type.VAR_INT, entityID);
wrapper.write(Types1_9.METADATA_LIST, metadataList);
MetadataRewriter.transform(getClientEntityTypes().get(entityID), metadataList);
handleMetadata(entityID, metadataList);
if (metadataList.size() > 0) {
try {
wrapper.send(Protocol1_9TO1_8.class);
} catch (Exception e) {
e.printStackTrace();
}
}
metadataBuffer.remove(entityID);
}
}
public int getProvidedEntityId() {
try {
return Via.getManager().getProviders().get(EntityIdProvider.class).getEntityId(getUser());
} catch (Exception e) {
return entityID;
}
}
}
| fix #1052
| common/src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/storage/EntityTracker.java | fix #1052 | <ide><path>ommon/src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/storage/EntityTracker.java
<ide> } else {
<ide> wrapper.write(Type.BYTE, (byte) 3);
<ide> }
<del> wrapper.write(Type.VAR_INT, 1); // player count
<del> wrapper.write(Type.STRING, getUser().get(ProtocolInfo.class).getUsername());
<add> wrapper.write(Type.STRING_ARRAY, new String[] {getUser().get(ProtocolInfo.class).getUsername()});
<ide> } else {
<ide> wrapper.write(Type.BYTE, (byte) 1); // remove team
<ide> } |
|
Java | mit | 85a485eefadca96091319eb425354912e887a088 | 0 | RiceKab/project-geowars,RiceKab/project-geowars | package be.howest.twentytwo.parametergame.model.component;
import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Pool.Poolable;
/**
* Sprite / Texture data
*/
public class SpriteComponent implements Component, Poolable {
public static final ComponentMapper<SpriteComponent> MAPPER = ComponentMapper.getFor(SpriteComponent.class);
private TextureRegion region; // TextureRegion for sprite sheet reasons
public TextureRegion getRegion() {
return region;
}
public void setRegion(TextureRegion region) {
this.region = region;
}
@Override
public void reset() {
// Need to reset? Should be set by factory anyway.
}
}
| projects/parametergame/core/src/be/howest/twentytwo/parametergame/model/component/SpriteComponent.java | package be.howest.twentytwo.parametergame.model.component;
import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Pool.Poolable;
/**
* Sprite / Texture data
*/
public class SpriteComponent implements Component, Poolable {
// TODO: Should I rename this TextureRegionComponent? This could create confusion with actual Sprite class
public static final ComponentMapper<SpriteComponent> MAPPER = ComponentMapper.getFor(SpriteComponent.class);
private TextureRegion region; // TextureRegion for sprite sheet reasons
public TextureRegion getRegion() {
return region;
}
public void setRegion(TextureRegion region) {
this.region = region;
}
@Override
public void reset() {
// Need to reset? Should be set by factory anyway.
}
}
| Moved ComponentMapper into Component classes.
| projects/parametergame/core/src/be/howest/twentytwo/parametergame/model/component/SpriteComponent.java | Moved ComponentMapper into Component classes. | <ide><path>rojects/parametergame/core/src/be/howest/twentytwo/parametergame/model/component/SpriteComponent.java
<ide> * Sprite / Texture data
<ide> */
<ide> public class SpriteComponent implements Component, Poolable {
<del> // TODO: Should I rename this TextureRegionComponent? This could create confusion with actual Sprite class
<ide>
<ide> public static final ComponentMapper<SpriteComponent> MAPPER = ComponentMapper.getFor(SpriteComponent.class);
<ide> |
|
Java | apache-2.0 | 0a9ecf01fa06e3c6782d5d9c1a1ca88aceb97092 | 0 | rmansoor/pentaho-kettle,alina-ipatina/pentaho-kettle,SergeyTravin/pentaho-kettle,e-cuellar/pentaho-kettle,cjsonger/pentaho-kettle,nicoben/pentaho-kettle,mkambol/pentaho-kettle,matthewtckr/pentaho-kettle,nicoben/pentaho-kettle,bmorrise/pentaho-kettle,lgrill-pentaho/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,rmansoor/pentaho-kettle,ViswesvarSekar/pentaho-kettle,emartin-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,tkafalas/pentaho-kettle,dkincade/pentaho-kettle,DFieldFL/pentaho-kettle,mbatchelor/pentaho-kettle,Advent51/pentaho-kettle,ddiroma/pentaho-kettle,pentaho/pentaho-kettle,wseyler/pentaho-kettle,ViswesvarSekar/pentaho-kettle,rmansoor/pentaho-kettle,mdamour1976/pentaho-kettle,zlcnju/kettle,pavel-sakun/pentaho-kettle,ddiroma/pentaho-kettle,roboguy/pentaho-kettle,brosander/pentaho-kettle,wseyler/pentaho-kettle,SergeyTravin/pentaho-kettle,ccaspanello/pentaho-kettle,denisprotopopov/pentaho-kettle,kurtwalker/pentaho-kettle,HiromuHota/pentaho-kettle,tmcsantos/pentaho-kettle,nicoben/pentaho-kettle,mkambol/pentaho-kettle,ddiroma/pentaho-kettle,graimundo/pentaho-kettle,nicoben/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mdamour1976/pentaho-kettle,marcoslarsen/pentaho-kettle,tmcsantos/pentaho-kettle,pavel-sakun/pentaho-kettle,marcoslarsen/pentaho-kettle,emartin-pentaho/pentaho-kettle,denisprotopopov/pentaho-kettle,skofra0/pentaho-kettle,pavel-sakun/pentaho-kettle,stepanovdg/pentaho-kettle,brosander/pentaho-kettle,emartin-pentaho/pentaho-kettle,cjsonger/pentaho-kettle,tkafalas/pentaho-kettle,flbrino/pentaho-kettle,Advent51/pentaho-kettle,pentaho/pentaho-kettle,bmorrise/pentaho-kettle,mdamour1976/pentaho-kettle,HiromuHota/pentaho-kettle,Advent51/pentaho-kettle,ccaspanello/pentaho-kettle,SergeyTravin/pentaho-kettle,emartin-pentaho/pentaho-kettle,alina-ipatina/pentaho-kettle,kurtwalker/pentaho-kettle,graimundo/pentaho-kettle,brosander/pentaho-kettle,pminutillo/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,matthewtckr/pentaho-kettle,skofra0/pentaho-kettle,cjsonger/pentaho-kettle,skofra0/pentaho-kettle,pavel-sakun/pentaho-kettle,tkafalas/pentaho-kettle,pedrofvteixeira/pentaho-kettle,SergeyTravin/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,marcoslarsen/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,tkafalas/pentaho-kettle,aminmkhan/pentaho-kettle,stepanovdg/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,roboguy/pentaho-kettle,mbatchelor/pentaho-kettle,stepanovdg/pentaho-kettle,matthewtckr/pentaho-kettle,wseyler/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,stevewillcock/pentaho-kettle,flbrino/pentaho-kettle,DFieldFL/pentaho-kettle,matthewtckr/pentaho-kettle,mbatchelor/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,stevewillcock/pentaho-kettle,pminutillo/pentaho-kettle,tmcsantos/pentaho-kettle,graimundo/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,flbrino/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,zlcnju/kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,kurtwalker/pentaho-kettle,zlcnju/kettle,ddiroma/pentaho-kettle,lgrill-pentaho/pentaho-kettle,hudak/pentaho-kettle,pedrofvteixeira/pentaho-kettle,mkambol/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,e-cuellar/pentaho-kettle,pminutillo/pentaho-kettle,zlcnju/kettle,DFieldFL/pentaho-kettle,mbatchelor/pentaho-kettle,e-cuellar/pentaho-kettle,graimundo/pentaho-kettle,bmorrise/pentaho-kettle,alina-ipatina/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,hudak/pentaho-kettle,pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,roboguy/pentaho-kettle,brosander/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,ViswesvarSekar/pentaho-kettle,kurtwalker/pentaho-kettle,flbrino/pentaho-kettle,stevewillcock/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,stepanovdg/pentaho-kettle,pminutillo/pentaho-kettle,stevewillcock/pentaho-kettle,cjsonger/pentaho-kettle,DFieldFL/pentaho-kettle,ccaspanello/pentaho-kettle,aminmkhan/pentaho-kettle,mdamour1976/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,dkincade/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,hudak/pentaho-kettle,roboguy/pentaho-kettle,denisprotopopov/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,e-cuellar/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ViswesvarSekar/pentaho-kettle,aminmkhan/pentaho-kettle,pentaho/pentaho-kettle,alina-ipatina/pentaho-kettle,mkambol/pentaho-kettle,hudak/pentaho-kettle,rmansoor/pentaho-kettle,Advent51/pentaho-kettle,aminmkhan/pentaho-kettle,bmorrise/pentaho-kettle,denisprotopopov/pentaho-kettle,tmcsantos/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,dkincade/pentaho-kettle,HiromuHota/pentaho-kettle,HiromuHota/pentaho-kettle,dkincade/pentaho-kettle | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.selectvalues;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.injection.Injection;
import org.pentaho.di.core.injection.InjectionDeep;
import org.pentaho.di.core.injection.InjectionSupported;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.lineage.FieldnameLineage;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
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;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
/**
* Meta Data class for the Select Values Step.
*
* Created on 02-jun-2003
*/
@InjectionSupported( localizationPrefix = "SelectValues.Injection.", groups = { "FIELDS", "REMOVES", "METAS" } )
public class SelectValuesMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = SelectValuesMeta.class; // for i18n purposes, needed by Translator2!!
public static final int UNDEFINED = -2;
// SELECT mode
@InjectionDeep
private SelectField[] selectFields = {};
/**
* Select: flag to indicate that the non-selected fields should also be taken along, ordered by fieldname
*/
@Injection( name = "SELECT_UNSPECIFIED" )
private boolean selectingAndSortingUnspecifiedFields;
// DE-SELECT mode
/** Names of the fields to be removed! */
@Injection( name = "REMOVE_NAME", group = "REMOVES" )
private String[] deleteName = {};
// META-DATA mode
@InjectionDeep
private SelectMetadataChange[] meta = {};
public SelectValuesMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the deleteName.
*/
public String[] getDeleteName() {
return deleteName;
}
/**
* @param deleteName
* The deleteName to set.
*/
public void setDeleteName( String[] deleteName ) {
this.deleteName = deleteName;
}
/**
* @param selectName
* The selectName to set.
*/
public void setSelectName( String[] selectName ) {
resizeSelectFields( selectName.length );
for ( int i = 0; i < selectFields.length; i++ ) {
selectFields[i].setName( selectName[i] );
}
}
public String[] getSelectName() {
String[] selectName = new String[selectFields.length];
for ( int i = 0; i < selectName.length; i++ ) {
selectName[i] = selectFields[i].getName();
}
return selectName;
}
/**
* @param selectRename
* The selectRename to set.
*/
public void setSelectRename( String[] selectRename ) {
if ( selectRename.length > selectFields.length ) {
resizeSelectFields( selectRename.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectRename.length ) {
selectFields[i].setRename( selectRename[i] );
} else {
selectFields[i].setRename( null );
}
}
}
public String[] getSelectRename() {
String[] selectRename = new String[selectFields.length];
for ( int i = 0; i < selectRename.length; i++ ) {
selectRename[i] = selectFields[i].getRename();
}
return selectRename;
}
/**
* @param selectLength
* The selectLength to set.
*/
public void setSelectLength( int[] selectLength ) {
if ( selectLength.length > selectFields.length ) {
resizeSelectFields( selectLength.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectLength.length ) {
selectFields[i].setLength( selectLength[i] );
} else {
selectFields[i].setLength( UNDEFINED );
}
}
}
public int[] getSelectLength() {
int[] selectLength = new int[selectFields.length];
for ( int i = 0; i < selectLength.length; i++ ) {
selectLength[i] = selectFields[i].getLength();
}
return selectLength;
}
/**
* @param selectPrecision
* The selectPrecision to set.
*/
public void setSelectPrecision( int[] selectPrecision ) {
if ( selectPrecision.length > selectFields.length ) {
resizeSelectFields( selectPrecision.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectPrecision.length ) {
selectFields[i].setPrecision( selectPrecision[i] );
} else {
selectFields[i].setPrecision( UNDEFINED );
}
}
}
public int[] getSelectPrecision() {
int[] selectPrecision = new int[selectFields.length];
for ( int i = 0; i < selectPrecision.length; i++ ) {
selectPrecision[i] = selectFields[i].getPrecision();
}
return selectPrecision;
}
private void resizeSelectFields( int length ) {
int fillStartIndex = selectFields.length;
selectFields = Arrays.copyOf( selectFields, length );
for ( int i = fillStartIndex; i < selectFields.length; i++ ) {
selectFields[i] = new SelectField();
selectFields[i].setLength( UNDEFINED );
selectFields[i].setPrecision( UNDEFINED );
}
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
}
public void allocate( int nrFields, int nrRemove, int nrMeta ) {
allocateSelect( nrFields );
allocateRemove( nrRemove );
allocateMeta( nrMeta );
}
private void allocateSelect( int nrFields ) {
selectFields = new SelectField[nrFields];
for ( int i = 0; i < nrFields; i++ ) {
selectFields[i] = new SelectField();
}
}
private void allocateRemove( int nrRemove ) {
deleteName = new String[nrRemove];
}
private void allocateMeta( int nrMeta ) {
meta = new SelectMetadataChange[nrMeta];
for ( int i = 0; i < nrMeta; i++ ) {
meta[i] = new SelectMetadataChange( this );
}
}
public Object clone() {
SelectValuesMeta retval = (SelectValuesMeta) super.clone();
int nrfields = selectFields.length;
int nrremove = deleteName.length;
int nrmeta = meta.length;
retval.allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
retval.getSelectFields()[i] = selectFields[i].clone();
}
System.arraycopy( deleteName, 0, retval.deleteName, 0, nrremove );
for ( int i = 0; i < nrmeta; i++ ) {
// CHECKSTYLE:Indentation:OFF
retval.getMeta()[i] = meta[i].clone();
}
return retval;
}
private void readData( Node step ) throws KettleXMLException {
try {
Node fields = XMLHandler.getSubNode( step, "fields" );
int nrfields = XMLHandler.countNodes( fields, "field" );
int nrremove = XMLHandler.countNodes( fields, "remove" );
int nrmeta = XMLHandler.countNodes( fields, SelectMetadataChange.XML_TAG );
allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
Node line = XMLHandler.getSubNodeByNr( fields, "field", i );
selectFields[i] = new SelectField();
selectFields[i].setName( XMLHandler.getTagValue( line, "name" ) );
selectFields[i].setRename( XMLHandler.getTagValue( line, "rename" ) );
selectFields[i].setLength( Const.toInt( XMLHandler.getTagValue( line, "length" ), UNDEFINED ) ); // $NON-NtagLS-1$
selectFields[i].setPrecision( Const.toInt( XMLHandler.getTagValue( line, "precision" ), UNDEFINED ) );
}
selectingAndSortingUnspecifiedFields =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( fields, "select_unspecified" ) );
for ( int i = 0; i < nrremove; i++ ) {
Node line = XMLHandler.getSubNodeByNr( fields, "remove", i );
deleteName[i] = XMLHandler.getTagValue( line, "name" );
}
for ( int i = 0; i < nrmeta; i++ ) {
Node metaNode = XMLHandler.getSubNodeByNr( fields, SelectMetadataChange.XML_TAG, i );
meta[i] = new SelectMetadataChange( this );
meta[i].loadXML( metaNode );
}
} catch ( Exception e ) {
throw new KettleXMLException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnableToReadStepInfoFromXML" ), e );
}
}
public void setDefault() {
allocate( 0, 0, 0 );
}
public void getSelectFields( RowMetaInterface inputRowMeta, String name ) throws KettleStepException {
RowMetaInterface row;
if ( selectFields != null && selectFields.length > 0 ) { // SELECT values
// 0. Start with an empty row
// 1. Keep only the selected values
// 2. Rename the selected values
// 3. Keep the order in which they are specified... (not the input order!)
//
row = new RowMeta();
for ( int i = 0; i < selectFields.length; i++ ) {
ValueMetaInterface v = inputRowMeta.searchValueMeta( selectFields[i].getName() );
if ( v != null ) { // We found the value
v = v.clone();
// Do we need to rename ?
if ( !v.getName().equals( selectFields[i].getRename() ) && selectFields[i].getRename() != null
&& selectFields[i].getRename().length() > 0 ) {
v.setName( selectFields[i].getRename() );
v.setOrigin( name );
}
if ( selectFields[i].getLength() != UNDEFINED ) {
v.setLength( selectFields[i].getLength() );
v.setOrigin( name );
}
if ( selectFields[i].getPrecision() != UNDEFINED ) {
v.setPrecision( selectFields[i].getPrecision() );
v.setOrigin( name );
}
// Add to the resulting row!
row.addValueMeta( v );
}
}
if ( selectingAndSortingUnspecifiedFields ) {
// Select the unspecified fields.
// Sort the fields
// Add them after the specified fields...
//
List<String> extra = new ArrayList<String>();
for ( int i = 0; i < inputRowMeta.size(); i++ ) {
String fieldName = inputRowMeta.getValueMeta( i ).getName();
if ( Const.indexOfString( fieldName, getSelectName() ) < 0 ) {
extra.add( fieldName );
}
}
Collections.sort( extra );
for ( String fieldName : extra ) {
ValueMetaInterface extraValue = inputRowMeta.searchValueMeta( fieldName );
row.addValueMeta( extraValue );
}
}
// OK, now remove all from r and re-add row:
inputRowMeta.clear();
inputRowMeta.addRowMeta( row );
}
}
public void getDeleteFields( RowMetaInterface inputRowMeta ) throws KettleStepException {
if ( deleteName != null && deleteName.length > 0 ) { // DESELECT values from the stream...
for ( int i = 0; i < deleteName.length; i++ ) {
try {
inputRowMeta.removeValueMeta( deleteName[i] );
} catch ( KettleValueException e ) {
throw new KettleStepException( e );
}
}
}
}
public void getMetadataFields( RowMetaInterface inputRowMeta, String name ) throws KettlePluginException {
if ( meta != null && meta.length > 0 ) {
// METADATA mode: change the meta-data of the values mentioned...
for ( int i = 0; i < meta.length; i++ ) {
SelectMetadataChange metaChange = meta[i];
int idx = inputRowMeta.indexOfValue( metaChange.getName() );
if ( idx >= 0 ) { // We found the value
// This is the value we need to change:
ValueMetaInterface v = inputRowMeta.getValueMeta( idx );
// Do we need to rename ?
if ( !v.getName().equals( metaChange.getRename() ) && !Const.isEmpty( metaChange.getRename() ) ) {
v.setName( metaChange.getRename() );
v.setOrigin( name );
}
// Change the type?
if ( metaChange.getType() != ValueMetaInterface.TYPE_NONE && v.getType() != metaChange.getType() ) {
v = ValueMetaFactory.cloneValueMeta( v, metaChange.getType() );
// This is now a copy, replace it in the row!
//
inputRowMeta.setValueMeta( idx, v );
// This also moves the data to normal storage type
//
v.setStorageType( ValueMetaInterface.STORAGE_TYPE_NORMAL );
}
if ( metaChange.getLength() != UNDEFINED ) {
v.setLength( metaChange.getLength() );
v.setOrigin( name );
}
if ( metaChange.getPrecision() != UNDEFINED ) {
v.setPrecision( metaChange.getPrecision() );
v.setOrigin( name );
}
if ( metaChange.getStorageType() >= 0 ) {
v.setStorageType( metaChange.getStorageType() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getConversionMask() ) ) {
v.setConversionMask( metaChange.getConversionMask() );
v.setOrigin( name );
}
v.setDateFormatLenient( metaChange.isDateFormatLenient() );
v.setDateFormatLocale( EnvUtil.createLocale( metaChange.getDateFormatLocale() ) );
v.setDateFormatTimeZone( EnvUtil.createTimeZone( metaChange.getDateFormatTimeZone() ) );
v.setLenientStringToNumber( metaChange.isLenientStringToNumber() );
if ( !Const.isEmpty( metaChange.getEncoding() ) ) {
v.setStringEncoding( metaChange.getEncoding() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getDecimalSymbol() ) ) {
v.setDecimalSymbol( metaChange.getDecimalSymbol() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getGroupingSymbol() ) ) {
v.setGroupingSymbol( metaChange.getGroupingSymbol() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getCurrencySymbol() ) ) {
v.setCurrencySymbol( metaChange.getCurrencySymbol() );
v.setOrigin( name );
}
}
}
}
}
public void getFields( RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
try {
RowMetaInterface rowMeta = inputRowMeta.clone();
inputRowMeta.clear();
inputRowMeta.addRowMeta( rowMeta );
getSelectFields( inputRowMeta, name );
getDeleteFields( inputRowMeta );
getMetadataFields( inputRowMeta, name );
} catch ( Exception e ) {
throw new KettleStepException( e );
}
}
public String getXML() {
StringBuilder retval = new StringBuilder( 300 );
retval.append( " <fields>" );
for ( int i = 0; i < selectFields.length; i++ ) {
retval.append( " <field>" );
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_NAME" ), selectFields[i]
.getName() ) );
if ( selectFields[i].getRename() != null ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_RENAME" ), selectFields[i]
.getRename() ) );
}
if ( selectFields[i].getPrecision() > 0 ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_LENGTH" ), selectFields[i]
.getLength() ) );
}
if ( selectFields[i].getPrecision() > 0 ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_PRECISION" ), selectFields[i]
.getPrecision() ) );
}
retval.append( " </field>" );
}
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "SELECT_UNSPECIFIED" ),
selectingAndSortingUnspecifiedFields ) );
for ( int i = 0; i < deleteName.length; i++ ) {
retval.append( " <remove>" );
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "REMOVE_NAME" ), deleteName[i] ) );
retval.append( " </remove>" );
}
for ( int i = 0; i < meta.length; i++ ) {
retval.append( meta[i].getXML() );
}
retval.append( " </fields>" );
return retval.toString();
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
try {
int nrfields = rep.countNrStepAttributes( id_step, getRepCode( "FIELD_NAME" ) );
int nrremove = rep.countNrStepAttributes( id_step, getRepCode( "REMOVE_NAME" ) );
int nrmeta = rep.countNrStepAttributes( id_step, getRepCode( "META_NAME" ) );
allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
selectFields[i].setName( rep.getStepAttributeString( id_step, i, getRepCode( "FIELD_NAME" ) ) );
selectFields[i].setRename( rep.getStepAttributeString( id_step, i, getRepCode( "FIELD_RENAME" ) ) );
selectFields[i].setLength( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "FIELD_LENGTH" ) ) );
selectFields[i].setPrecision( (int) rep.getStepAttributeInteger( id_step, i, getRepCode(
"FIELD_PRECISION" ) ) );
}
selectingAndSortingUnspecifiedFields = rep.getStepAttributeBoolean( id_step, getRepCode( "SELECT_UNSPECIFIED" ) );
for ( int i = 0; i < nrremove; i++ ) {
deleteName[i] = rep.getStepAttributeString( id_step, i, getRepCode( "REMOVE_NAME" ) );
}
for ( int i = 0; i < nrmeta; i++ ) {
meta[i] = new SelectMetadataChange( this );
meta[i].setName( rep.getStepAttributeString( id_step, i, getRepCode( "META_NAME" ) ) );
meta[i].setRename( rep.getStepAttributeString( id_step, i, getRepCode( "META_RENAME" ) ) );
meta[i].setType( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_TYPE" ) ) );
meta[i].setLength( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_LENGTH" ) ) );
meta[i].setPrecision( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_PRECISION" ) ) );
meta[i].setStorageType( ValueMeta.getStorageType( rep.getStepAttributeString( id_step, i, getRepCode(
"META_STORAGE_TYPE" ) ) ) );
meta[i].setConversionMask( rep.getStepAttributeString( id_step, i, getRepCode( "META_CONVERSION_MASK" ) ) );
meta[i].setDateFormatLenient( Boolean.parseBoolean( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_LENIENT" ) ) ) );
meta[i].setDateFormatLocale( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_LOCALE" ) ) );
meta[i].setDateFormatTimeZone( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_TIMEZONE" ) ) );
meta[i].setLenientStringToNumber( Boolean.parseBoolean( rep.getStepAttributeString( id_step, i, getRepCode(
"META_LENIENT_STRING_TO_NUMBER" ) ) ) );
meta[i].setDecimalSymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_DECIMAL" ) ) );
meta[i].setGroupingSymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_GROUPING" ) ) );
meta[i].setCurrencySymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_CURRENCY" ) ) );
meta[i].setEncoding( rep.getStepAttributeString( id_step, i, getRepCode( "META_ENCODING" ) ) );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository" ), e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step )
throws KettleException {
try {
for ( int i = 0; i < selectFields.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_NAME" ), selectFields[i].getName() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_RENAME" ), selectFields[i]
.getRename() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_LENGTH" ), selectFields[i]
.getLength() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_PRECISION" ), selectFields[i]
.getPrecision() );
}
rep.saveStepAttribute( id_transformation, id_step, getRepCode( "SELECT_UNSPECIFIED" ),
selectingAndSortingUnspecifiedFields );
for ( int i = 0; i < deleteName.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "REMOVE_NAME" ), deleteName[i] );
}
for ( int i = 0; i < meta.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_NAME" ), meta[i].getName() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_RENAME" ), meta[i].getRename() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_TYPE" ), meta[i].getType() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_LENGTH" ), meta[i].getLength() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_PRECISION" ), meta[i].getPrecision() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_STORAGE_TYPE" ), ValueMeta
.getStorageTypeCode( meta[i].getStorageType() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_CONVERSION_MASK" ), meta[i]
.getConversionMask() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_LENIENT" ), Boolean
.toString( meta[i].isDateFormatLenient() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_LOCALE" ), meta[i]
.getDateFormatLocale() == null ? null : meta[i].getDateFormatLocale().toString() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_TIMEZONE" ), meta[i]
.getDateFormatTimeZone() == null ? null : meta[i].getDateFormatTimeZone().toString() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_LENIENT_STRING_TO_NUMBER" ), Boolean
.toString( meta[i].isLenientStringToNumber() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DECIMAL" ), meta[i]
.getDecimalSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_GROUPING" ), meta[i]
.getGroupingSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_CURRENCY" ), meta[i]
.getCurrencySymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_ENCODING" ), meta[i].getEncoding() );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnableToSaveStepInfoToRepository" ) + id_step, e );
}
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev,
String[] input, String[] output, RowMetaInterface info, VariableSpace space, Repository repository,
IMetaStore metaStore ) {
CheckResult cr;
if ( prev != null && prev.size() > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.StepReceivingFields", prev.size() + "" ), stepMeta );
remarks.add( cr );
/*
* Take care of the normal SELECT fields...
*/
String error_message = "";
boolean error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.selectFields.length; i++ ) {
int idx = prev.indexOfValue( selectFields[i].getName() );
if ( idx < 0 ) {
error_message += "\t\t" + selectFields[i].getName() + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.SelectedFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllSelectedFieldsFound" ), stepMeta );
remarks.add( cr );
}
if ( this.selectFields.length > 0 ) {
// Starting from prev...
for ( int i = 0; i < prev.size(); i++ ) {
ValueMetaInterface pv = prev.getValueMeta( i );
int idx = Const.indexOfString( pv.getName(), getSelectName() );
if ( idx < 0 ) {
error_message += "\t\t" + pv.getName() + " (" + pv.getTypeDesc() + ")" + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.FieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_COMMENT, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllSelectedFieldsFound2" ), stepMeta );
remarks.add( cr );
}
}
/*
* How about the DE-SELECT (remove) fields...
*/
error_message = "";
error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.deleteName.length; i++ ) {
int idx = prev.indexOfValue( deleteName[i] );
if ( idx < 0 ) {
error_message += "\t\t" + deleteName[i] + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.DeSelectedFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllDeSelectedFieldsFound" ), stepMeta );
remarks.add( cr );
}
/*
* How about the Meta-fields...?
*/
error_message = "";
error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.meta.length; i++ ) {
int idx = prev.indexOfValue( this.meta[i].getName() );
if ( idx < 0 ) {
error_message += "\t\t" + this.meta[i].getName() + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.MetadataFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllMetadataFieldsFound" ), stepMeta );
remarks.add( cr );
}
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.FieldsNotFound2" ), stepMeta );
remarks.add( cr );
}
// See if we have input streams leading to this step!
if ( input.length > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.StepReceivingInfoFromOtherSteps" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.NoInputReceivedError" ), stepMeta );
remarks.add( cr );
}
// Check for doubles in the selected fields...
int[] cnt = new int[selectFields.length];
boolean error_found = false;
String error_message = "";
for ( int i = 0; i < selectFields.length; i++ ) {
cnt[i] = 0;
for ( int j = 0; j < selectFields.length; j++ ) {
if ( selectFields[i].getName().equals( selectFields[j].getName() ) ) {
cnt[i]++;
}
}
if ( cnt[i] > 1 ) {
if ( !error_found ) { // first time...
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.DuplicateFieldsSpecified" ) + Const.CR;
} else {
error_found = true;
}
error_message +=
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.OccurentRow", i + " : " + selectFields[i]
.getName() + " (" + cnt[i] ) + Const.CR;
error_found = true;
}
}
if ( error_found ) {
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
}
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta,
Trans trans ) {
return new SelectValues( stepMeta, stepDataInterface, cnr, transMeta, trans );
}
public StepDataInterface getStepData() {
return new SelectValuesData();
}
/**
* @return the selectingAndSortingUnspecifiedFields
*/
public boolean isSelectingAndSortingUnspecifiedFields() {
return selectingAndSortingUnspecifiedFields;
}
/**
* @param selectingAndSortingUnspecifiedFields
* the selectingAndSortingUnspecifiedFields to set
*/
public void setSelectingAndSortingUnspecifiedFields( boolean selectingAndSortingUnspecifiedFields ) {
this.selectingAndSortingUnspecifiedFields = selectingAndSortingUnspecifiedFields;
}
/**
* @return the meta
*/
public SelectMetadataChange[] getMeta() {
return meta;
}
/**
* @param meta
* the meta to set
*/
public void setMeta( SelectMetadataChange[] meta ) {
this.meta = meta;
}
public boolean supportsErrorHandling() {
return true;
}
public SelectField[] getSelectFields() {
return selectFields;
}
public void setSelectFields( SelectField[] selectFields ) {
this.selectFields = selectFields;
}
/**
* We will describe in which way the field names change between input and output in this step.
*
* @return The list of field name lineage objects
*/
public List<FieldnameLineage> getFieldnameLineage() {
List<FieldnameLineage> lineages = new ArrayList<FieldnameLineage>();
// Select values...
//
for ( int i = 0; i < selectFields.length; i++ ) {
String input = selectFields[i].getName();
String output = selectFields[i].getRename();
// See if the select tab renames a column!
//
if ( !Const.isEmpty( output ) && !input.equalsIgnoreCase( output ) ) {
// Yes, add it to the list
//
lineages.add( new FieldnameLineage( input, output ) );
}
}
// Metadata
//
for ( int i = 0; i < getMeta().length; i++ ) {
String input = getMeta()[i].getName();
String output = getMeta()[i].getRename();
// See if the select tab renames a column!
//
if ( !Const.isEmpty( output ) && !input.equalsIgnoreCase( output ) ) {
// See if the input is not the output of a row in the Select tab
//
int idx = Const.indexOfString( input, getSelectRename() );
if ( idx < 0 ) {
// nothing special, add it to the list
//
lineages.add( new FieldnameLineage( input, output ) );
} else {
// Modify the existing field name lineage entry
//
FieldnameLineage lineage = FieldnameLineage.findFieldnameLineageWithInput( lineages, input );
lineage.setOutputFieldname( output );
}
}
}
return lineages;
}
public static class SelectField implements Cloneable {
/** Select: Name of the selected field */
@Injection( name = "FIELD_NAME", group = "FIELDS" )
private String name;
/** Select: Rename to ... */
@Injection( name = "FIELD_RENAME", group = "FIELDS" )
private String rename;
/** Select: length of field */
@Injection( name = "FIELD_LENGTH", group = "FIELDS" )
private int length;
/** Select: Precision of field (for numbers) */
@Injection( name = "FIELD_PRECISION", group = "FIELDS" )
private int precision;
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getRename() {
return rename;
}
public void setRename( String rename ) {
this.rename = rename;
}
public int getLength() {
return length;
}
public void setLength( int length ) {
this.length = length;
}
public int getPrecision() {
return precision;
}
public void setPrecision( int precision ) {
this.precision = precision;
}
public SelectField clone() {
try {
return (SelectField) super.clone();
} catch ( CloneNotSupportedException e ) {
throw new RuntimeException( e );
}
}
}
}
| engine/src/org/pentaho/di/trans/steps/selectvalues/SelectValuesMeta.java | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.selectvalues;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.injection.Injection;
import org.pentaho.di.core.injection.InjectionDeep;
import org.pentaho.di.core.injection.InjectionSupported;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.lineage.FieldnameLineage;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
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;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
/**
* Meta Data class for the Select Values Step.
*
* Created on 02-jun-2003
*/
@InjectionSupported( localizationPrefix = "SelectValues.Injection.", groups = { "FIELDS", "REMOVES", "METAS" } )
public class SelectValuesMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = SelectValuesMeta.class; // for i18n purposes, needed by Translator2!!
// SELECT mode
@InjectionDeep
private SelectField[] selectFields = {};
/**
* Select: flag to indicate that the non-selected fields should also be taken along, ordered by fieldname
*/
@Injection( name = "SELECT_UNSPECIFIED" )
private boolean selectingAndSortingUnspecifiedFields;
// DE-SELECT mode
/** Names of the fields to be removed! */
@Injection( name = "REMOVE_NAME", group = "REMOVES" )
private String[] deleteName = {};
// META-DATA mode
@InjectionDeep
private SelectMetadataChange[] meta = {};
public SelectValuesMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the deleteName.
*/
public String[] getDeleteName() {
return deleteName;
}
/**
* @param deleteName
* The deleteName to set.
*/
public void setDeleteName( String[] deleteName ) {
this.deleteName = deleteName;
}
/**
* @param selectName
* The selectName to set.
*/
public void setSelectName( String[] selectName ) {
resizeSelectFields( selectName.length );
for ( int i = 0; i < selectFields.length; i++ ) {
selectFields[i].setName( selectName[i] );
}
}
public String[] getSelectName() {
List<String> names = new ArrayList<String>();
for ( int i = 0; i < selectFields.length; i++ ) {
String value = selectFields[i].getName();
if ( value == null ) {
break;
}
names.add( value );
}
return names.toArray( new String[names.size()] );
}
/**
* @param selectRename
* The selectRename to set.
*/
public void setSelectRename( String[] selectRename ) {
if ( selectRename.length > selectFields.length ) {
resizeSelectFields( selectRename.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectRename.length ) {
selectFields[i].setRename( selectRename[i] );
} else {
selectFields[i].setRename( null );
}
}
}
public String[] getSelectRename() {
List<String> renames = new ArrayList<String>();
for ( int i = 0; i < selectFields.length; i++ ) {
String value = selectFields[i].getRename();
if ( value == null ) {
break;
}
renames.add( value );
}
return renames.toArray( new String[renames.size()] );
}
/**
* @param selectLength
* The selectLength to set.
*/
public void setSelectLength( int[] selectLength ) {
if ( selectLength.length > selectFields.length ) {
resizeSelectFields( selectLength.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectLength.length ) {
selectFields[i].setLength( selectLength[i] );
} else {
selectFields[i].setLength( -2 );
}
}
}
public int[] getSelectLength() {
List<Integer> lengths = new ArrayList<Integer>();
for ( int i = 0; i < selectFields.length; i++ ) {
int value = selectFields[i].getLength();
if ( value == -2 ) {
break;
}
lengths.add( value );
}
int[] lengthsArray = new int[lengths.size()];
for ( int i = 0; i < lengthsArray.length; i++ ) {
lengthsArray[i] = lengths.get( i );
}
return lengthsArray;
}
/**
* @param selectPrecision
* The selectPrecision to set.
*/
public void setSelectPrecision( int[] selectPrecision ) {
if ( selectPrecision.length > selectFields.length ) {
resizeSelectFields( selectPrecision.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectPrecision.length ) {
selectFields[i].setPrecision( selectPrecision[i] );
} else {
selectFields[i].setPrecision( -2 );
}
}
}
public int[] getSelectPrecision() {
List<Integer> precisions = new ArrayList<Integer>();
for ( int i = 0; i < selectFields.length; i++ ) {
int value = selectFields[i].getPrecision();
if ( value == -2 ) {
break;
}
precisions.add( value );
}
int[] precisionsArray = new int[precisions.size()];
for ( int i = 0; i < precisionsArray.length; i++ ) {
precisionsArray[i] = precisions.get( i );
}
return precisionsArray;
}
private void resizeSelectFields( int length ) {
int fillStartIndex = selectFields.length;
selectFields = Arrays.copyOf( selectFields, length );
for ( int i = fillStartIndex; i < selectFields.length; i++ ) {
selectFields[i] = new SelectField();
selectFields[i].setLength( -2 );
selectFields[i].setPrecision( -2 );
}
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
}
public void allocate( int nrFields, int nrRemove, int nrMeta ) {
allocateSelect( nrFields );
allocateRemove( nrRemove );
allocateMeta( nrMeta );
}
private void allocateSelect( int nrFields ) {
selectFields = new SelectField[nrFields];
for ( int i = 0; i < nrFields; i++ ) {
selectFields[i] = new SelectField();
}
}
private void allocateRemove( int nrRemove ) {
deleteName = new String[nrRemove];
}
private void allocateMeta( int nrMeta ) {
meta = new SelectMetadataChange[nrMeta];
for ( int i = 0; i < nrMeta; i++ ) {
meta[i] = new SelectMetadataChange( this );
}
}
public Object clone() {
SelectValuesMeta retval = (SelectValuesMeta) super.clone();
int nrfields = selectFields.length;
int nrremove = deleteName.length;
int nrmeta = meta.length;
retval.allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
retval.getSelectFields()[i] = selectFields[i].clone();
}
System.arraycopy( deleteName, 0, retval.deleteName, 0, nrremove );
for ( int i = 0; i < nrmeta; i++ ) {
// CHECKSTYLE:Indentation:OFF
retval.getMeta()[i] = meta[i].clone();
}
return retval;
}
private void readData( Node step ) throws KettleXMLException {
try {
Node fields = XMLHandler.getSubNode( step, "fields" );
int nrfields = XMLHandler.countNodes( fields, "field" );
int nrremove = XMLHandler.countNodes( fields, "remove" );
int nrmeta = XMLHandler.countNodes( fields, SelectMetadataChange.XML_TAG );
allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
Node line = XMLHandler.getSubNodeByNr( fields, "field", i );
selectFields[i] = new SelectField();
selectFields[i].setName( XMLHandler.getTagValue( line, "name" ) );
selectFields[i].setRename( XMLHandler.getTagValue( line, "rename" ) );
selectFields[i].setLength( Const.toInt( XMLHandler.getTagValue( line, "length" ), -2 ) ); // $NON-NtagLS-1$
selectFields[i].setPrecision( Const.toInt( XMLHandler.getTagValue( line, "precision" ), -2 ) );
}
selectingAndSortingUnspecifiedFields =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( fields, "select_unspecified" ) );
for ( int i = 0; i < nrremove; i++ ) {
Node line = XMLHandler.getSubNodeByNr( fields, "remove", i );
deleteName[i] = XMLHandler.getTagValue( line, "name" );
}
for ( int i = 0; i < nrmeta; i++ ) {
Node metaNode = XMLHandler.getSubNodeByNr( fields, SelectMetadataChange.XML_TAG, i );
meta[i] = new SelectMetadataChange( this );
meta[i].loadXML( metaNode );
}
} catch ( Exception e ) {
throw new KettleXMLException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnableToReadStepInfoFromXML" ), e );
}
}
public void setDefault() {
allocate( 0, 0, 0 );
}
public void getSelectFields( RowMetaInterface inputRowMeta, String name ) throws KettleStepException {
RowMetaInterface row;
if ( selectFields != null && selectFields.length > 0 ) { // SELECT values
// 0. Start with an empty row
// 1. Keep only the selected values
// 2. Rename the selected values
// 3. Keep the order in which they are specified... (not the input order!)
//
row = new RowMeta();
for ( int i = 0; i < selectFields.length; i++ ) {
ValueMetaInterface v = inputRowMeta.searchValueMeta( selectFields[i].getName() );
if ( v != null ) { // We found the value
v = v.clone();
// Do we need to rename ?
if ( !v.getName().equals( selectFields[i].getRename() ) && selectFields[i].getRename() != null
&& selectFields[i].getRename().length() > 0 ) {
v.setName( selectFields[i].getRename() );
v.setOrigin( name );
}
if ( selectFields[i].getLength() != -2 ) {
v.setLength( selectFields[i].getLength() );
v.setOrigin( name );
}
if ( selectFields[i].getPrecision() != -2 ) {
v.setPrecision( selectFields[i].getPrecision() );
v.setOrigin( name );
}
// Add to the resulting row!
row.addValueMeta( v );
}
}
if ( selectingAndSortingUnspecifiedFields ) {
// Select the unspecified fields.
// Sort the fields
// Add them after the specified fields...
//
List<String> extra = new ArrayList<String>();
for ( int i = 0; i < inputRowMeta.size(); i++ ) {
String fieldName = inputRowMeta.getValueMeta( i ).getName();
if ( Const.indexOfString( fieldName, getSelectName() ) < 0 ) {
extra.add( fieldName );
}
}
Collections.sort( extra );
for ( String fieldName : extra ) {
ValueMetaInterface extraValue = inputRowMeta.searchValueMeta( fieldName );
row.addValueMeta( extraValue );
}
}
// OK, now remove all from r and re-add row:
inputRowMeta.clear();
inputRowMeta.addRowMeta( row );
}
}
public void getDeleteFields( RowMetaInterface inputRowMeta ) throws KettleStepException {
if ( deleteName != null && deleteName.length > 0 ) { // DESELECT values from the stream...
for ( int i = 0; i < deleteName.length; i++ ) {
try {
inputRowMeta.removeValueMeta( deleteName[i] );
} catch ( KettleValueException e ) {
throw new KettleStepException( e );
}
}
}
}
public void getMetadataFields( RowMetaInterface inputRowMeta, String name ) throws KettlePluginException {
if ( meta != null && meta.length > 0 ) {
// METADATA mode: change the meta-data of the values mentioned...
for ( int i = 0; i < meta.length; i++ ) {
SelectMetadataChange metaChange = meta[i];
int idx = inputRowMeta.indexOfValue( metaChange.getName() );
if ( idx >= 0 ) { // We found the value
// This is the value we need to change:
ValueMetaInterface v = inputRowMeta.getValueMeta( idx );
// Do we need to rename ?
if ( !v.getName().equals( metaChange.getRename() ) && !Const.isEmpty( metaChange.getRename() ) ) {
v.setName( metaChange.getRename() );
v.setOrigin( name );
}
// Change the type?
if ( metaChange.getType() != ValueMetaInterface.TYPE_NONE && v.getType() != metaChange.getType() ) {
v = ValueMetaFactory.cloneValueMeta( v, metaChange.getType() );
// This is now a copy, replace it in the row!
//
inputRowMeta.setValueMeta( idx, v );
// This also moves the data to normal storage type
//
v.setStorageType( ValueMetaInterface.STORAGE_TYPE_NORMAL );
}
if ( metaChange.getLength() != -2 ) {
v.setLength( metaChange.getLength() );
v.setOrigin( name );
}
if ( metaChange.getPrecision() != -2 ) {
v.setPrecision( metaChange.getPrecision() );
v.setOrigin( name );
}
if ( metaChange.getStorageType() >= 0 ) {
v.setStorageType( metaChange.getStorageType() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getConversionMask() ) ) {
v.setConversionMask( metaChange.getConversionMask() );
v.setOrigin( name );
}
v.setDateFormatLenient( metaChange.isDateFormatLenient() );
v.setDateFormatLocale( EnvUtil.createLocale( metaChange.getDateFormatLocale() ) );
v.setDateFormatTimeZone( EnvUtil.createTimeZone( metaChange.getDateFormatTimeZone() ) );
v.setLenientStringToNumber( metaChange.isLenientStringToNumber() );
if ( !Const.isEmpty( metaChange.getEncoding() ) ) {
v.setStringEncoding( metaChange.getEncoding() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getDecimalSymbol() ) ) {
v.setDecimalSymbol( metaChange.getDecimalSymbol() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getGroupingSymbol() ) ) {
v.setGroupingSymbol( metaChange.getGroupingSymbol() );
v.setOrigin( name );
}
if ( !Const.isEmpty( metaChange.getCurrencySymbol() ) ) {
v.setCurrencySymbol( metaChange.getCurrencySymbol() );
v.setOrigin( name );
}
}
}
}
}
public void getFields( RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
try {
RowMetaInterface rowMeta = inputRowMeta.clone();
inputRowMeta.clear();
inputRowMeta.addRowMeta( rowMeta );
getSelectFields( inputRowMeta, name );
getDeleteFields( inputRowMeta );
getMetadataFields( inputRowMeta, name );
} catch ( Exception e ) {
throw new KettleStepException( e );
}
}
public String getXML() {
StringBuilder retval = new StringBuilder( 300 );
retval.append( " <fields>" );
for ( int i = 0; i < selectFields.length; i++ ) {
retval.append( " <field>" );
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_NAME" ), selectFields[i]
.getName() ) );
if ( selectFields[i].getRename() != null ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_RENAME" ), selectFields[i]
.getRename() ) );
}
if ( selectFields[i].getPrecision() > 0 ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_LENGTH" ), selectFields[i]
.getLength() ) );
}
if ( selectFields[i].getPrecision() > 0 ) {
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "FIELD_PRECISION" ), selectFields[i]
.getPrecision() ) );
}
retval.append( " </field>" );
}
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "SELECT_UNSPECIFIED" ),
selectingAndSortingUnspecifiedFields ) );
for ( int i = 0; i < deleteName.length; i++ ) {
retval.append( " <remove>" );
retval.append( " " ).append( XMLHandler.addTagValue( getXmlCode( "REMOVE_NAME" ), deleteName[i] ) );
retval.append( " </remove>" );
}
for ( int i = 0; i < meta.length; i++ ) {
retval.append( meta[i].getXML() );
}
retval.append( " </fields>" );
return retval.toString();
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
try {
int nrfields = rep.countNrStepAttributes( id_step, getRepCode( "FIELD_NAME" ) );
int nrremove = rep.countNrStepAttributes( id_step, getRepCode( "REMOVE_NAME" ) );
int nrmeta = rep.countNrStepAttributes( id_step, getRepCode( "META_NAME" ) );
allocate( nrfields, nrremove, nrmeta );
for ( int i = 0; i < nrfields; i++ ) {
selectFields[i].setName( rep.getStepAttributeString( id_step, i, getRepCode( "FIELD_NAME" ) ) );
selectFields[i].setRename( rep.getStepAttributeString( id_step, i, getRepCode( "FIELD_RENAME" ) ) );
selectFields[i].setLength( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "FIELD_LENGTH" ) ) );
selectFields[i].setPrecision( (int) rep.getStepAttributeInteger( id_step, i, getRepCode(
"FIELD_PRECISION" ) ) );
}
selectingAndSortingUnspecifiedFields = rep.getStepAttributeBoolean( id_step, getRepCode( "SELECT_UNSPECIFIED" ) );
for ( int i = 0; i < nrremove; i++ ) {
deleteName[i] = rep.getStepAttributeString( id_step, i, getRepCode( "REMOVE_NAME" ) );
}
for ( int i = 0; i < nrmeta; i++ ) {
meta[i] = new SelectMetadataChange( this );
meta[i].setName( rep.getStepAttributeString( id_step, i, getRepCode( "META_NAME" ) ) );
meta[i].setRename( rep.getStepAttributeString( id_step, i, getRepCode( "META_RENAME" ) ) );
meta[i].setType( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_TYPE" ) ) );
meta[i].setLength( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_LENGTH" ) ) );
meta[i].setPrecision( (int) rep.getStepAttributeInteger( id_step, i, getRepCode( "META_PRECISION" ) ) );
meta[i].setStorageType( ValueMeta.getStorageType( rep.getStepAttributeString( id_step, i, getRepCode(
"META_STORAGE_TYPE" ) ) ) );
meta[i].setConversionMask( rep.getStepAttributeString( id_step, i, getRepCode( "META_CONVERSION_MASK" ) ) );
meta[i].setDateFormatLenient( Boolean.parseBoolean( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_LENIENT" ) ) ) );
meta[i].setDateFormatLocale( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_LOCALE" ) ) );
meta[i].setDateFormatTimeZone( rep.getStepAttributeString( id_step, i, getRepCode(
"META_DATE_FORMAT_TIMEZONE" ) ) );
meta[i].setLenientStringToNumber( Boolean.parseBoolean( rep.getStepAttributeString( id_step, i, getRepCode(
"META_LENIENT_STRING_TO_NUMBER" ) ) ) );
meta[i].setDecimalSymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_DECIMAL" ) ) );
meta[i].setGroupingSymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_GROUPING" ) ) );
meta[i].setCurrencySymbol( rep.getStepAttributeString( id_step, i, getRepCode( "META_CURRENCY" ) ) );
meta[i].setEncoding( rep.getStepAttributeString( id_step, i, getRepCode( "META_ENCODING" ) ) );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository" ), e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step )
throws KettleException {
try {
for ( int i = 0; i < selectFields.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_NAME" ), selectFields[i].getName() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_RENAME" ), selectFields[i]
.getRename() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_LENGTH" ), selectFields[i]
.getLength() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "FIELD_PRECISION" ), selectFields[i]
.getPrecision() );
}
rep.saveStepAttribute( id_transformation, id_step, getRepCode( "SELECT_UNSPECIFIED" ),
selectingAndSortingUnspecifiedFields );
for ( int i = 0; i < deleteName.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "REMOVE_NAME" ), deleteName[i] );
}
for ( int i = 0; i < meta.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_NAME" ), meta[i].getName() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_RENAME" ), meta[i].getRename() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_TYPE" ), meta[i].getType() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_LENGTH" ), meta[i].getLength() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_PRECISION" ), meta[i].getPrecision() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_STORAGE_TYPE" ), ValueMeta
.getStorageTypeCode( meta[i].getStorageType() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_CONVERSION_MASK" ), meta[i]
.getConversionMask() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_LENIENT" ), Boolean
.toString( meta[i].isDateFormatLenient() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_LOCALE" ), meta[i]
.getDateFormatLocale() == null ? null : meta[i].getDateFormatLocale().toString() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DATE_FORMAT_TIMEZONE" ), meta[i]
.getDateFormatTimeZone() == null ? null : meta[i].getDateFormatTimeZone().toString() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_LENIENT_STRING_TO_NUMBER" ), Boolean
.toString( meta[i].isLenientStringToNumber() ) );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_DECIMAL" ), meta[i]
.getDecimalSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_GROUPING" ), meta[i]
.getGroupingSymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_CURRENCY" ), meta[i]
.getCurrencySymbol() );
rep.saveStepAttribute( id_transformation, id_step, i, getRepCode( "META_ENCODING" ), meta[i].getEncoding() );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG,
"SelectValuesMeta.Exception.UnableToSaveStepInfoToRepository" ) + id_step, e );
}
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev,
String[] input, String[] output, RowMetaInterface info, VariableSpace space, Repository repository,
IMetaStore metaStore ) {
CheckResult cr;
if ( prev != null && prev.size() > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.StepReceivingFields", prev.size() + "" ), stepMeta );
remarks.add( cr );
/*
* Take care of the normal SELECT fields...
*/
String error_message = "";
boolean error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.selectFields.length; i++ ) {
int idx = prev.indexOfValue( selectFields[i].getName() );
if ( idx < 0 ) {
error_message += "\t\t" + selectFields[i].getName() + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.SelectedFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllSelectedFieldsFound" ), stepMeta );
remarks.add( cr );
}
if ( this.selectFields.length > 0 ) {
// Starting from prev...
for ( int i = 0; i < prev.size(); i++ ) {
ValueMetaInterface pv = prev.getValueMeta( i );
int idx = Const.indexOfString( pv.getName(), getSelectName() );
if ( idx < 0 ) {
error_message += "\t\t" + pv.getName() + " (" + pv.getTypeDesc() + ")" + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.FieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_COMMENT, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllSelectedFieldsFound2" ), stepMeta );
remarks.add( cr );
}
}
/*
* How about the DE-SELECT (remove) fields...
*/
error_message = "";
error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.deleteName.length; i++ ) {
int idx = prev.indexOfValue( deleteName[i] );
if ( idx < 0 ) {
error_message += "\t\t" + deleteName[i] + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.DeSelectedFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllDeSelectedFieldsFound" ), stepMeta );
remarks.add( cr );
}
/*
* How about the Meta-fields...?
*/
error_message = "";
error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < this.meta.length; i++ ) {
int idx = prev.indexOfValue( this.meta[i].getName() );
if ( idx < 0 ) {
error_message += "\t\t" + this.meta[i].getName() + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.MetadataFieldsNotFound" ) + Const.CR + Const.CR
+ error_message;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.AllMetadataFieldsFound" ), stepMeta );
remarks.add( cr );
}
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.FieldsNotFound2" ), stepMeta );
remarks.add( cr );
}
// See if we have input streams leading to this step!
if ( input.length > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.StepReceivingInfoFromOtherSteps" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString( PKG,
"SelectValuesMeta.CheckResult.NoInputReceivedError" ), stepMeta );
remarks.add( cr );
}
// Check for doubles in the selected fields...
int[] cnt = new int[selectFields.length];
boolean error_found = false;
String error_message = "";
for ( int i = 0; i < selectFields.length; i++ ) {
cnt[i] = 0;
for ( int j = 0; j < selectFields.length; j++ ) {
if ( selectFields[i].getName().equals( selectFields[j].getName() ) ) {
cnt[i]++;
}
}
if ( cnt[i] > 1 ) {
if ( !error_found ) { // first time...
error_message =
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.DuplicateFieldsSpecified" ) + Const.CR;
} else {
error_found = true;
}
error_message +=
BaseMessages.getString( PKG, "SelectValuesMeta.CheckResult.OccurentRow", i + " : " + selectFields[i]
.getName() + " (" + cnt[i] ) + Const.CR;
error_found = true;
}
}
if ( error_found ) {
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
}
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta,
Trans trans ) {
return new SelectValues( stepMeta, stepDataInterface, cnr, transMeta, trans );
}
public StepDataInterface getStepData() {
return new SelectValuesData();
}
/**
* @return the selectingAndSortingUnspecifiedFields
*/
public boolean isSelectingAndSortingUnspecifiedFields() {
return selectingAndSortingUnspecifiedFields;
}
/**
* @param selectingAndSortingUnspecifiedFields
* the selectingAndSortingUnspecifiedFields to set
*/
public void setSelectingAndSortingUnspecifiedFields( boolean selectingAndSortingUnspecifiedFields ) {
this.selectingAndSortingUnspecifiedFields = selectingAndSortingUnspecifiedFields;
}
/**
* @return the meta
*/
public SelectMetadataChange[] getMeta() {
return meta;
}
/**
* @param meta
* the meta to set
*/
public void setMeta( SelectMetadataChange[] meta ) {
this.meta = meta;
}
public boolean supportsErrorHandling() {
return true;
}
public SelectField[] getSelectFields() {
return selectFields;
}
public void setSelectFields( SelectField[] selectFields ) {
this.selectFields = selectFields;
}
/**
* We will describe in which way the field names change between input and output in this step.
*
* @return The list of field name lineage objects
*/
public List<FieldnameLineage> getFieldnameLineage() {
List<FieldnameLineage> lineages = new ArrayList<FieldnameLineage>();
// Select values...
//
for ( int i = 0; i < selectFields.length; i++ ) {
String input = selectFields[i].getName();
String output = selectFields[i].getRename();
// See if the select tab renames a column!
//
if ( !Const.isEmpty( output ) && !input.equalsIgnoreCase( output ) ) {
// Yes, add it to the list
//
lineages.add( new FieldnameLineage( input, output ) );
}
}
// Metadata
//
for ( int i = 0; i < getMeta().length; i++ ) {
String input = getMeta()[i].getName();
String output = getMeta()[i].getRename();
// See if the select tab renames a column!
//
if ( !Const.isEmpty( output ) && !input.equalsIgnoreCase( output ) ) {
// See if the input is not the output of a row in the Select tab
//
int idx = Const.indexOfString( input, getSelectRename() );
if ( idx < 0 ) {
// nothing special, add it to the list
//
lineages.add( new FieldnameLineage( input, output ) );
} else {
// Modify the existing field name lineage entry
//
FieldnameLineage lineage = FieldnameLineage.findFieldnameLineageWithInput( lineages, input );
lineage.setOutputFieldname( output );
}
}
}
return lineages;
}
public static class SelectField implements Cloneable {
/** Select: Name of the selected field */
@Injection( name = "FIELD_NAME", group = "FIELDS" )
private String name;
/** Select: Rename to ... */
@Injection( name = "FIELD_RENAME", group = "FIELDS" )
private String rename;
/** Select: length of field */
@Injection( name = "FIELD_LENGTH", group = "FIELDS" )
private int length;
/** Select: Precision of field (for numbers) */
@Injection( name = "FIELD_PRECISION", group = "FIELDS" )
private int precision;
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getRename() {
return rename;
}
public void setRename( String rename ) {
this.rename = rename;
}
public int getLength() {
return length;
}
public void setLength( int length ) {
this.length = length;
}
public int getPrecision() {
return precision;
}
public void setPrecision( int precision ) {
this.precision = precision;
}
public SelectField clone() {
try {
return (SelectField) super.clone();
} catch ( CloneNotSupportedException e ) {
throw new RuntimeException( e );
}
}
}
}
| [PDI-15032] - Metadata Injection on all tabs of select values step is causing error - fix getters
| engine/src/org/pentaho/di/trans/steps/selectvalues/SelectValuesMeta.java | [PDI-15032] - Metadata Injection on all tabs of select values step is causing error - fix getters | <ide><path>ngine/src/org/pentaho/di/trans/steps/selectvalues/SelectValuesMeta.java
<ide> public class SelectValuesMeta extends BaseStepMeta implements StepMetaInterface {
<ide> private static Class<?> PKG = SelectValuesMeta.class; // for i18n purposes, needed by Translator2!!
<ide>
<add> public static final int UNDEFINED = -2;
<add>
<ide> // SELECT mode
<ide> @InjectionDeep
<ide> private SelectField[] selectFields = {};
<ide> }
<ide>
<ide> public String[] getSelectName() {
<del> List<String> names = new ArrayList<String>();
<del> for ( int i = 0; i < selectFields.length; i++ ) {
<del> String value = selectFields[i].getName();
<del> if ( value == null ) {
<del> break;
<del> }
<del> names.add( value );
<del> }
<del> return names.toArray( new String[names.size()] );
<add> String[] selectName = new String[selectFields.length];
<add> for ( int i = 0; i < selectName.length; i++ ) {
<add> selectName[i] = selectFields[i].getName();
<add> }
<add> return selectName;
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> public String[] getSelectRename() {
<del> List<String> renames = new ArrayList<String>();
<del> for ( int i = 0; i < selectFields.length; i++ ) {
<del> String value = selectFields[i].getRename();
<del> if ( value == null ) {
<del> break;
<del> }
<del> renames.add( value );
<del> }
<del> return renames.toArray( new String[renames.size()] );
<add> String[] selectRename = new String[selectFields.length];
<add> for ( int i = 0; i < selectRename.length; i++ ) {
<add> selectRename[i] = selectFields[i].getRename();
<add> }
<add> return selectRename;
<ide> }
<ide>
<ide> /**
<ide> if ( i < selectLength.length ) {
<ide> selectFields[i].setLength( selectLength[i] );
<ide> } else {
<del> selectFields[i].setLength( -2 );
<add> selectFields[i].setLength( UNDEFINED );
<ide> }
<ide> }
<ide> }
<ide>
<ide> public int[] getSelectLength() {
<del> List<Integer> lengths = new ArrayList<Integer>();
<del> for ( int i = 0; i < selectFields.length; i++ ) {
<del> int value = selectFields[i].getLength();
<del> if ( value == -2 ) {
<del> break;
<del> }
<del> lengths.add( value );
<del> }
<del> int[] lengthsArray = new int[lengths.size()];
<del> for ( int i = 0; i < lengthsArray.length; i++ ) {
<del> lengthsArray[i] = lengths.get( i );
<del> }
<del> return lengthsArray;
<add> int[] selectLength = new int[selectFields.length];
<add> for ( int i = 0; i < selectLength.length; i++ ) {
<add> selectLength[i] = selectFields[i].getLength();
<add> }
<add> return selectLength;
<ide> }
<ide>
<ide> /**
<ide> if ( i < selectPrecision.length ) {
<ide> selectFields[i].setPrecision( selectPrecision[i] );
<ide> } else {
<del> selectFields[i].setPrecision( -2 );
<add> selectFields[i].setPrecision( UNDEFINED );
<ide> }
<ide> }
<ide> }
<ide>
<ide> public int[] getSelectPrecision() {
<del> List<Integer> precisions = new ArrayList<Integer>();
<del> for ( int i = 0; i < selectFields.length; i++ ) {
<del> int value = selectFields[i].getPrecision();
<del> if ( value == -2 ) {
<del> break;
<del> }
<del> precisions.add( value );
<del> }
<del> int[] precisionsArray = new int[precisions.size()];
<del> for ( int i = 0; i < precisionsArray.length; i++ ) {
<del> precisionsArray[i] = precisions.get( i );
<del> }
<del> return precisionsArray;
<add> int[] selectPrecision = new int[selectFields.length];
<add> for ( int i = 0; i < selectPrecision.length; i++ ) {
<add> selectPrecision[i] = selectFields[i].getPrecision();
<add> }
<add> return selectPrecision;
<ide> }
<ide>
<ide> private void resizeSelectFields( int length ) {
<ide> selectFields = Arrays.copyOf( selectFields, length );
<ide> for ( int i = fillStartIndex; i < selectFields.length; i++ ) {
<ide> selectFields[i] = new SelectField();
<del> selectFields[i].setLength( -2 );
<del> selectFields[i].setPrecision( -2 );
<add> selectFields[i].setLength( UNDEFINED );
<add> selectFields[i].setPrecision( UNDEFINED );
<ide> }
<ide> }
<ide>
<ide> selectFields[i] = new SelectField();
<ide> selectFields[i].setName( XMLHandler.getTagValue( line, "name" ) );
<ide> selectFields[i].setRename( XMLHandler.getTagValue( line, "rename" ) );
<del> selectFields[i].setLength( Const.toInt( XMLHandler.getTagValue( line, "length" ), -2 ) ); // $NON-NtagLS-1$
<del> selectFields[i].setPrecision( Const.toInt( XMLHandler.getTagValue( line, "precision" ), -2 ) );
<add> selectFields[i].setLength( Const.toInt( XMLHandler.getTagValue( line, "length" ), UNDEFINED ) ); // $NON-NtagLS-1$
<add> selectFields[i].setPrecision( Const.toInt( XMLHandler.getTagValue( line, "precision" ), UNDEFINED ) );
<ide> }
<ide> selectingAndSortingUnspecifiedFields =
<ide> "Y".equalsIgnoreCase( XMLHandler.getTagValue( fields, "select_unspecified" ) );
<ide> v.setName( selectFields[i].getRename() );
<ide> v.setOrigin( name );
<ide> }
<del> if ( selectFields[i].getLength() != -2 ) {
<add> if ( selectFields[i].getLength() != UNDEFINED ) {
<ide> v.setLength( selectFields[i].getLength() );
<ide> v.setOrigin( name );
<ide> }
<del> if ( selectFields[i].getPrecision() != -2 ) {
<add> if ( selectFields[i].getPrecision() != UNDEFINED ) {
<ide> v.setPrecision( selectFields[i].getPrecision() );
<ide> v.setOrigin( name );
<ide> }
<ide> //
<ide> v.setStorageType( ValueMetaInterface.STORAGE_TYPE_NORMAL );
<ide> }
<del> if ( metaChange.getLength() != -2 ) {
<add> if ( metaChange.getLength() != UNDEFINED ) {
<ide> v.setLength( metaChange.getLength() );
<ide> v.setOrigin( name );
<ide> }
<del> if ( metaChange.getPrecision() != -2 ) {
<add> if ( metaChange.getPrecision() != UNDEFINED ) {
<ide> v.setPrecision( metaChange.getPrecision() );
<ide> v.setOrigin( name );
<ide> } |
|
Java | epl-1.0 | f1bb5583895fa38bc025400bc7d377c362ff9be7 | 0 | QPark/EIP | /*******************************************************************************
* Copyright (c) 2013, 2014, 2015 QPark Consulting S.a r.l. This program and the
* accompanying materials are made available under the terms of the Eclipse
* Public License v1.0. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package com.qpark.maven.plugin.mockoperation;
import java.io.File;
import java.util.Objects;
import java.util.Optional;
import org.apache.maven.plugin.logging.Log;
import com.qpark.maven.Util;
import com.qpark.maven.xmlbeans.ComplexType;
import com.qpark.maven.xmlbeans.ComplexTypeChild;
import com.qpark.maven.xmlbeans.ElementType;
import com.qpark.maven.xmlbeans.XsdsUtil;
/**
* @author bhausen
*/
public class OperationProviderMockGenerator {
private final Log log;
private final XsdsUtil config;
private ComplexType ctRequest;
private ComplexType ctResponse;
private final ElementType elementRequest;
private ElementType elementResponse = null;
private String fqRequestType;
private String fqResponseType;
private final String methodName;
private final String packageName;
private String requestType;
private String responseType;
private final String operationName;
private final String serviceId;
private final File outputDirectory;
private final boolean useInsightAnnotation;
private final String eipVersion;
public OperationProviderMockGenerator(final XsdsUtil config,
final File outputDirectory, final ElementType element,
final boolean useInsightAnnotation, final String eipVersion,
final Log log) {
this.config = config;
this.outputDirectory = outputDirectory;
this.log = log;
this.elementRequest = element;
this.packageName = element.getPackageNameMockOperationProvider();
this.operationName = element.getOperationName();
this.serviceId = element.getServiceId();
this.methodName = element.getMethodName();
this.useInsightAnnotation = useInsightAnnotation;
this.eipVersion = eipVersion;
this.elementResponse = XsdsUtil.findResponse(this.elementRequest,
config.getElementTypes(), config);
if (this.elementResponse != null) {
this.ctRequest = new ComplexType(
this.elementRequest.getElement().getType(), this.config);
this.ctResponse = new ComplexType(
this.elementResponse.getElement().getType(), this.config);
this.fqRequestType = this.ctRequest.getClassNameFullQualified();
this.fqResponseType = this.ctResponse.getClassNameFullQualified();
this.requestType = this.ctRequest.getClassName();
this.responseType = this.ctResponse.getClassName();
}
}
public void generate() {
this.log.debug("+generate");
if (this.elementResponse != null && this.ctResponse != null
&& !this.ctResponse.isSimpleType()
&& !this.ctResponse.isPrimitiveType()) {
StringBuffer sb = new StringBuffer(1024);
sb.append("package ");
sb.append(this.packageName);
sb.append(";\n");
sb.append("\n");
sb.append("import java.io.StringReader;\n");
sb.append("import java.util.concurrent.TimeUnit;\n");
sb.append("\n");
sb.append("import javax.xml.bind.JAXBContext;\n");
sb.append("import javax.xml.bind.JAXBElement;\n");
sb.append("import javax.xml.bind.JAXBException;\n");
sb.append("import javax.xml.bind.Unmarshaller;\n");
sb.append("\n");
sb.append(
"import org.springframework.beans.factory.annotation.Autowired;\n");
// sb.append("import
// org.springframework.beans.factory.annotation.Qualifier;\n");
sb.append(
"import org.springframework.integration.annotation.ServiceActivator;\n");
sb.append("import org.springframework.stereotype.Component;\n");
sb.append("\n");
sb.append("import ");
sb.append(this.fqRequestType);
sb.append(";\n");
sb.append("import ");
sb.append(this.fqResponseType);
sb.append(";\n");
sb.append("import ");
sb.append(this.elementRequest.getPackageName());
sb.append(".ObjectFactory;\n");
if (this.useInsightAnnotation) {
sb.append(
"import com.springsource.insight.annotation.InsightEndPoint;\n");
}
sb.append("\n");
sb.append("/**\n");
sb.append(" * Operation ");
sb.append(Util.splitOnCapital(this.methodName));
sb.append(" on service <code>");
sb.append(this.serviceId);
sb.append("</code>.\n");
sb.append(Util.getGeneratedAtJavaDocClassHeader(this.getClass(),
this.eipVersion));
sb.append(" */\n");
sb.append("//@Component(\"");
sb.append(this.elementRequest.getBeanIdMockOperationProvider());
sb.append("\")\n");
sb.append("public class ");
sb.append(this.elementRequest.getClassNameMockOperationProvider());
sb.append(" {\n");
sb.append("\t/** The {@link Logger}. */\n");
sb.append(
"\tprivate final org.slf4j.Logger logger = org.slf4j.LoggerFactory\n");
sb.append("\t\t\t.getLogger(");
sb.append(this.elementRequest.getClassNameMockOperationProvider());
sb.append(".class);\n");
sb.append("\n");
sb.append(" /** The {@link ObjectFactory}. */\n");
sb.append(
" private final ObjectFactory of = new ObjectFactory();\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append(
"\t * @param message the {@link JAXBElement} containing a {@link ");
sb.append(this.requestType);
sb.append("}.\n");
sb.append("\t * @return the {@link JAXBElement} with a {@link ");
sb.append(this.responseType);
sb.append("}.\n");
sb.append("\t */\n");
if (this.useInsightAnnotation) {
sb.append(" @InsightEndPoint\n");
}
sb.append(" @ServiceActivator\n");
sb.append(" public final JAXBElement<");
sb.append(this.responseType);
sb.append("> ");
sb.append(this.methodName);
sb.append("(\n");
sb.append(" final JAXBElement<");
sb.append(this.requestType);
sb.append("> message) {\n");
sb.append("\t\tthis.logger.debug(\"+");
sb.append(this.methodName);
sb.append("\");\n");
sb.append("\t\t");
sb.append(this.requestType);
sb.append(" request = message.getValue();\n");
sb.append("\t\t");
sb.append(this.responseType);
sb.append(" response = this.of.\n\t\t\t\tcreate");
sb.append(this.responseType);
sb.append("();\n");
sb.append("\t\tlong start = System.currentTimeMillis();\n");
sb.append("\t\ttry {\n");
sb.append("\t\t\t");
sb.append(this.responseType);
sb.append(" responseSample = this.getSampleResponseObject();\n");
sb.append("\t\t\tif (responseSample != null) {\n");
sb.append("\t\t\t\tresponse = responseSample;\n");
sb.append("\t\t\t}\n");
sb.append("\t\t\t// response.getFailure().clear();\n");
sb.append(
"\t\t\t// The operation {0} of service {1} is not implement!!\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t//\tFailureHandler.getFailureType(\"E_NOT_IMPLEMENTED_OPERATION\", \n");
sb.append("\t\t\t//\t\t\"");
sb.append(Util.splitOnCapital(this.methodName));
sb.append("\", \"");
sb.append(this.serviceId);
sb.append("\"));\n");
sb.append("\t\t} catch (Throwable e) {\n");
sb.append("\t\t\t/* Add a not covered error to the response. */\n");
sb.append("\t\t\tthis.logger.error(e.getMessage(), e);\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t// FailureHandler.getFailureType(\"E_NOT_KNOWN_ERROR\", e);\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t// FailureHandler.handleException(e, \"E_NOT_KNOWN_ERROR\", this.logger);\n");
sb.append("\t\t} finally {\n");
sb.append("\t\t\tthis.logger.debug(\" ");
sb.append(this.methodName);
sb.append(" duration {}\",\n");
sb.append("\t\t\t\t\trequestDuration(start));\n");
sb.append("\t\t\tthis.logger.debug(\"-");
sb.append(this.methodName);
Optional<ComplexTypeChild> listChild = this.ctResponse.getChildren()
.stream()
.filter(ctc -> !ctc.getChildName().equals("failure")
&& ctc.isList())
.findFirst();
if (this.hasFailureList(this.ctResponse)) {
if (listChild.isPresent()) {
sb.append(" #{}, #f{}\",\n");
sb.append("\t\t\t\t\t");
sb.append("response/*.get");
sb.append(Util.capitalize(listChild.get().getChildName()));
sb.append("().size()*/,");
sb.append(" response.getFailure().size());\n");
} else {
sb.append(" #1, #f{}\",\n");
sb.append("\t\t\t\t\t");
sb.append(" response.getFailure().size());\n");
}
} else {
if (listChild.isPresent()) {
sb.append(" #{}, #f-\",\n");
sb.append("\t\t\t\t\t");
sb.append("response/*.get");
sb.append(Util.capitalize(listChild.get().getChildName()));
sb.append("().size()*/);\n");
} else {
sb.append(" #1, #f-\");\n");
}
}
sb.append("\t\t}\n");
sb.append(" return this.of\n");
sb.append(" .create");
sb.append(this.elementResponse.getClassNameObject());
sb.append("(response);\n");
sb.append(" }\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append("\t * @return a mock {@link ");
sb.append(this.responseType);
sb.append("}.\n");
sb.append("\t */\n");
sb.append("\tprivate ");
sb.append(this.responseType);
sb.append(" getSampleResponseObject() {\n");
sb.append("\t\t");
sb.append(this.responseType);
sb.append(" mock = null;\n");
sb.append("\t\tString xml = this.getSampleXml();\n");
sb.append("\t\ttry {\n");
sb.append("\t\t\tJAXBContext jaxbContext = JAXBContext\n");
sb.append("\t\t\t\t\t.newInstance(\"");
sb.append(this.ctRequest.getPackageName());
sb.append("\");\n");
sb.append(
"\t\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n");
sb.append("\t\t\tJAXBElement<");
sb.append(this.responseType);
sb.append("> jaxb = (JAXBElement<");
sb.append(this.responseType);
sb.append(">) unmarshaller.unmarshal(new StringReader(xml));\n");
sb.append("\t\t\tif (jaxb != null) {\n");
sb.append("\t\t\t\tmock = jaxb.getValue();\n");
sb.append("\t\t\t}\n");
sb.append("\t\t} catch (Exception e) {\n");
sb.append("\t\t\tthis.logger.debug(\"");
sb.append(this.operationName);
sb.append(
" generate sample message error: {}\", e.getMessage());\n");
sb.append("\t\t\tmock = null;\n");
sb.append("\t\t}\n");
sb.append("\t\treturn mock;\n");
sb.append("\t}\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append("\t * @return a sample xml.\n");
sb.append("\t */\n");
sb.append("\tprivate String getSampleXml() {\n");
sb.append(XsdsUtil.getSampleCodeing(this.ctResponse.getType(),
this.elementResponse.getElement().getName()
.getLocalPart()));
sb.append("\t\treturn sb.toString();\n");
sb.append("\t}\n");
sb.append("\t/**\n");
sb.append("\t * @param start\n");
sb.append("\t * @return the duration in 000:00:00.000 format.\n");
sb.append("\t */\n");
sb.append("\tprivate String requestDuration(final long start) {\n");
sb.append(
"\t\tlong millis = System.currentTimeMillis() - start;\n");
sb.append(
"\t\tString hmss = String.format(\"%03d:%02d:%02d.%03d\",TimeUnit.MILLISECONDS.toHours(millis),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toMillis(millis) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millis)));\n");
sb.append("\t\treturn hmss;\n");
sb.append("\t}\n");
sb.append("}\n");
sb.append("\n");
File f = Util.getFile(this.outputDirectory, this.packageName,
new StringBuffer()
.append(this.elementRequest
.getClassNameMockOperationProvider())
.append(".java").toString());
this.log.info(new StringBuffer().append("Write ")
.append(f.getAbsolutePath()));
try {
Util.writeToFile(f, sb.toString());
} catch (Exception e) {
this.log.error(e.getMessage());
e.printStackTrace();
}
this.log.debug("-generate");
}
}
private boolean hasFailureList(final ComplexType ct) {
boolean value = ct.getChildren().stream().filter(
ctc -> ctc.getChildName().equals("failure") && ctc.isList())
.findFirst().isPresent();
if (!value && Objects.nonNull(ct.getParent())) {
value = this.hasFailureList(ct.getParent());
}
return value;
}
}
| qp-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/mockoperation/OperationProviderMockGenerator.java | /*******************************************************************************
* Copyright (c) 2013, 2014, 2015 QPark Consulting S.a r.l. This program and the
* accompanying materials are made available under the terms of the Eclipse
* Public License v1.0. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package com.qpark.maven.plugin.mockoperation;
import java.io.File;
import org.apache.maven.plugin.logging.Log;
import com.qpark.maven.Util;
import com.qpark.maven.xmlbeans.ComplexType;
import com.qpark.maven.xmlbeans.ElementType;
import com.qpark.maven.xmlbeans.XsdsUtil;
/**
* @author bhausen
*/
public class OperationProviderMockGenerator {
private final Log log;
private final XsdsUtil config;
private ComplexType ctRequest;
private ComplexType ctResponse;
private final ElementType elementRequest;
private ElementType elementResponse = null;
private String fqRequestType;
private String fqResponseType;
private final String methodName;
private final String packageName;
private String requestType;
private String responseType;
private final String operationName;
private final String serviceId;
private final File outputDirectory;
private final boolean useInsightAnnotation;
private final String eipVersion;
public OperationProviderMockGenerator(final XsdsUtil config,
final File outputDirectory, final ElementType element,
final boolean useInsightAnnotation, final String eipVersion,
final Log log) {
this.config = config;
this.outputDirectory = outputDirectory;
this.log = log;
this.elementRequest = element;
this.packageName = element.getPackageNameMockOperationProvider();
this.operationName = element.getOperationName();
this.serviceId = element.getServiceId();
this.methodName = element.getMethodName();
this.useInsightAnnotation = useInsightAnnotation;
this.eipVersion = eipVersion;
this.elementResponse = XsdsUtil.findResponse(this.elementRequest,
config.getElementTypes(), config);
if (this.elementResponse != null) {
this.ctRequest = new ComplexType(
this.elementRequest.getElement().getType(), this.config);
this.ctResponse = new ComplexType(
this.elementResponse.getElement().getType(), this.config);
this.fqRequestType = this.ctRequest.getClassNameFullQualified();
this.fqResponseType = this.ctResponse.getClassNameFullQualified();
this.requestType = this.ctRequest.getClassName();
this.responseType = this.ctResponse.getClassName();
}
}
public void generate() {
this.log.debug("+generate");
if (this.elementResponse != null && this.ctResponse != null
&& !this.ctResponse.isSimpleType()
&& !this.ctResponse.isPrimitiveType()) {
StringBuffer sb = new StringBuffer(1024);
sb.append("package ");
sb.append(this.packageName);
sb.append(";\n");
sb.append("\n");
sb.append("import java.io.StringReader;\n");
sb.append("import java.util.concurrent.TimeUnit;\n");
sb.append("\n");
sb.append("import javax.xml.bind.JAXBContext;\n");
sb.append("import javax.xml.bind.JAXBElement;\n");
sb.append("import javax.xml.bind.JAXBException;\n");
sb.append("import javax.xml.bind.Unmarshaller;\n");
sb.append("\n");
sb.append(
"import org.springframework.beans.factory.annotation.Autowired;\n");
// sb.append("import
// org.springframework.beans.factory.annotation.Qualifier;\n");
sb.append(
"import org.springframework.integration.annotation.ServiceActivator;\n");
sb.append("import org.springframework.stereotype.Component;\n");
sb.append("\n");
sb.append("import ");
sb.append(this.fqRequestType);
sb.append(";\n");
sb.append("import ");
sb.append(this.fqResponseType);
sb.append(";\n");
sb.append("import ");
sb.append(this.elementRequest.getPackageName());
sb.append(".ObjectFactory;\n");
if (this.useInsightAnnotation) {
sb.append(
"import com.springsource.insight.annotation.InsightEndPoint;\n");
}
sb.append("\n");
sb.append("/**\n");
sb.append(" * Operation ");
sb.append(Util.splitOnCapital(this.methodName));
sb.append(" on service <code>");
sb.append(this.serviceId);
sb.append("</code>.\n");
sb.append(Util.getGeneratedAtJavaDocClassHeader(this.getClass(),
this.eipVersion));
sb.append(" */\n");
sb.append("//@Component(\"");
sb.append(this.elementRequest.getBeanIdMockOperationProvider());
sb.append("\")\n");
sb.append("public class ");
sb.append(this.elementRequest.getClassNameMockOperationProvider());
sb.append(" {\n");
sb.append("\t/** The {@link Logger}. */\n");
sb.append(
"\tprivate final org.slf4j.Logger logger = org.slf4j.LoggerFactory\n");
sb.append("\t\t\t.getLogger(");
sb.append(this.elementRequest.getClassNameMockOperationProvider());
sb.append(".class);\n");
sb.append("\n");
sb.append(" /** The {@link ObjectFactory}. */\n");
sb.append(
" private final ObjectFactory of = new ObjectFactory();\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append(
"\t * @param message the {@link JAXBElement} containing a {@link ");
sb.append(this.requestType);
sb.append("}.\n");
sb.append("\t * @return the {@link JAXBElement} with a {@link ");
sb.append(this.responseType);
sb.append("}.\n");
sb.append("\t */\n");
if (this.useInsightAnnotation) {
sb.append(" @InsightEndPoint\n");
}
sb.append(" @ServiceActivator\n");
sb.append(" public final JAXBElement<");
sb.append(this.responseType);
sb.append("> ");
sb.append(this.methodName);
sb.append("(\n");
sb.append(" final JAXBElement<");
sb.append(this.requestType);
sb.append("> message) {\n");
sb.append("\t\tthis.logger.debug(\"+");
sb.append(this.methodName);
sb.append("\");\n");
sb.append("\t\t");
sb.append(this.requestType);
sb.append(" request = message.getValue();\n");
sb.append("\t\t");
sb.append(this.responseType);
sb.append(" response = this.of.\n\t\t\t\tcreate");
sb.append(this.responseType);
sb.append("();\n");
sb.append("\t\tlong start = System.currentTimeMillis();\n");
sb.append("\t\ttry {\n");
sb.append("\t\t\t");
sb.append(this.responseType);
sb.append(" responseSample = this.getSampleResponseObject();\n");
sb.append("\t\t\tif (responseSample != null) {\n");
sb.append("\t\t\t\tresponse = responseSample;\n");
sb.append("\t\t\t}\n");
sb.append("\t\t\t// response.getFailure().clear();\n");
sb.append(
"\t\t\t// The operation {0} of service {1} is not implement!!\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t//\tFailureHandler.getFailureType(\"E_NOT_IMPLEMENTED_OPERATION\", \n");
sb.append("\t\t\t//\t\t\"");
sb.append(Util.splitOnCapital(this.methodName));
sb.append("\", \"");
sb.append(this.serviceId);
sb.append("\"));\n");
sb.append("\t\t} catch (Throwable e) {\n");
sb.append("\t\t\t/* Add a not covered error to the response. */\n");
sb.append("\t\t\tthis.logger.error(e.getMessage(), e);\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t// FailureHandler.getFailureType(\"E_NOT_KNOWN_ERROR\", e);\n");
sb.append("\t\t\t// response.getFailure().add(\n");
sb.append(
"\t\t\t// FailureHandler.handleException(e, \"E_NOT_KNOWN_ERROR\", this.logger);\n");
sb.append("\t\t} finally {\n");
sb.append("\t\t\tthis.logger.debug(\" ");
sb.append(this.methodName);
sb.append(" duration {}\",\n");
sb.append("\t\t\t\t\trequestDuration(start));\n");
sb.append("\t\t\tthis.logger.debug(\"-");
sb.append(this.methodName);
sb.append(" #{}, #f{}\",\n");
sb.append(
"\t\t\t\t\tresponse/*.get()*/ != null ? 1 : 0, response.getFailure()\n");
sb.append("\t\t\t\t\t\t\t.size());\n");
sb.append("\t\t}\n");
sb.append(" return this.of\n");
sb.append(" .create");
sb.append(this.elementResponse.getClassNameObject());
sb.append("(response);\n");
sb.append(" }\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append("\t * @return a mock {@link ");
sb.append(this.responseType);
sb.append("}.\n");
sb.append("\t */\n");
sb.append("\tprivate ");
sb.append(this.responseType);
sb.append(" getSampleResponseObject() {\n");
sb.append("\t\t");
sb.append(this.responseType);
sb.append(" mock = null;\n");
sb.append("\t\tString xml = this.getSampleXml();\n");
sb.append("\t\ttry {\n");
sb.append("\t\t\tJAXBContext jaxbContext = JAXBContext\n");
sb.append("\t\t\t\t\t.newInstance(\"");
sb.append(this.ctRequest.getPackageName());
sb.append("\");\n");
sb.append(
"\t\t\tUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();\n");
sb.append("\t\t\tJAXBElement<");
sb.append(this.responseType);
sb.append("> jaxb = (JAXBElement<");
sb.append(this.responseType);
sb.append(">) unmarshaller.unmarshal(new StringReader(xml));\n");
sb.append("\t\t\tif (jaxb != null) {\n");
sb.append("\t\t\t\tmock = jaxb.getValue();\n");
sb.append("\t\t\t}\n");
sb.append("\t\t} catch (Exception e) {\n");
sb.append("\t\t\tthis.logger.debug(\"");
sb.append(this.operationName);
sb.append(
" generate sample message error: {}\", e.getMessage());\n");
sb.append("\t\t\tmock = null;\n");
sb.append("\t\t}\n");
sb.append("\t\treturn mock;\n");
sb.append("\t}\n");
sb.append("\n");
sb.append("\t/**\n");
sb.append("\t * @return a sample xml.\n");
sb.append("\t */\n");
sb.append("\tprivate String getSampleXml() {\n");
sb.append(XsdsUtil.getSampleCodeing(this.ctResponse.getType(),
this.elementResponse.getElement().getName()
.getLocalPart()));
sb.append("\t\treturn sb.toString();\n");
sb.append("\t}\n");
sb.append("\t/**\n");
sb.append("\t * @param start\n");
sb.append("\t * @return the duration in 000:00:00.000 format.\n");
sb.append("\t */\n");
sb.append("\tprivate String requestDuration(final long start) {\n");
sb.append(
"\t\tlong millis = System.currentTimeMillis() - start;\n");
sb.append(
"\t\tString hmss = String.format(\"%03d:%02d:%02d.%03d\",TimeUnit.MILLISECONDS.toHours(millis),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)),\n");
sb.append(
"\t\t\tTimeUnit.MILLISECONDS.toMillis(millis) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millis)));\n");
sb.append("\t\treturn hmss;\n");
sb.append("\t}\n");
sb.append("}\n");
sb.append("\n");
File f = Util.getFile(this.outputDirectory, this.packageName,
new StringBuffer()
.append(this.elementRequest
.getClassNameMockOperationProvider())
.append(".java").toString());
this.log.info(new StringBuffer().append("Write ")
.append(f.getAbsolutePath()));
try {
Util.writeToFile(f, sb.toString());
} catch (Exception e) {
this.log.error(e.getMessage());
e.printStackTrace();
}
this.log.debug("-generate");
}
}
}
| MockGenerator: Generate mocks without having failure list
| qp-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/mockoperation/OperationProviderMockGenerator.java | MockGenerator: Generate mocks without having failure list | <ide><path>p-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/mockoperation/OperationProviderMockGenerator.java
<ide> package com.qpark.maven.plugin.mockoperation;
<ide>
<ide> import java.io.File;
<add>import java.util.Objects;
<add>import java.util.Optional;
<ide>
<ide> import org.apache.maven.plugin.logging.Log;
<ide>
<ide> import com.qpark.maven.Util;
<ide> import com.qpark.maven.xmlbeans.ComplexType;
<add>import com.qpark.maven.xmlbeans.ComplexTypeChild;
<ide> import com.qpark.maven.xmlbeans.ElementType;
<ide> import com.qpark.maven.xmlbeans.XsdsUtil;
<ide>
<ide>
<ide> sb.append("\t\t\tthis.logger.debug(\"-");
<ide> sb.append(this.methodName);
<del> sb.append(" #{}, #f{}\",\n");
<del> sb.append(
<del> "\t\t\t\t\tresponse/*.get()*/ != null ? 1 : 0, response.getFailure()\n");
<del> sb.append("\t\t\t\t\t\t\t.size());\n");
<add> Optional<ComplexTypeChild> listChild = this.ctResponse.getChildren()
<add> .stream()
<add> .filter(ctc -> !ctc.getChildName().equals("failure")
<add> && ctc.isList())
<add> .findFirst();
<add>
<add> if (this.hasFailureList(this.ctResponse)) {
<add> if (listChild.isPresent()) {
<add> sb.append(" #{}, #f{}\",\n");
<add> sb.append("\t\t\t\t\t");
<add> sb.append("response/*.get");
<add> sb.append(Util.capitalize(listChild.get().getChildName()));
<add> sb.append("().size()*/,");
<add> sb.append(" response.getFailure().size());\n");
<add> } else {
<add> sb.append(" #1, #f{}\",\n");
<add> sb.append("\t\t\t\t\t");
<add> sb.append(" response.getFailure().size());\n");
<add> }
<add> } else {
<add> if (listChild.isPresent()) {
<add> sb.append(" #{}, #f-\",\n");
<add> sb.append("\t\t\t\t\t");
<add> sb.append("response/*.get");
<add> sb.append(Util.capitalize(listChild.get().getChildName()));
<add> sb.append("().size()*/);\n");
<add> } else {
<add> sb.append(" #1, #f-\");\n");
<add> }
<add> }
<ide>
<ide> sb.append("\t\t}\n");
<ide>
<ide> this.log.debug("-generate");
<ide> }
<ide> }
<add>
<add> private boolean hasFailureList(final ComplexType ct) {
<add> boolean value = ct.getChildren().stream().filter(
<add> ctc -> ctc.getChildName().equals("failure") && ctc.isList())
<add> .findFirst().isPresent();
<add> if (!value && Objects.nonNull(ct.getParent())) {
<add> value = this.hasFailureList(ct.getParent());
<add> }
<add> return value;
<add> }
<ide> } |
|
Java | agpl-3.0 | 2699a4c5b94f6ae514070e83ec0efdf46780423c | 0 | SilverTeamWork/Silverpeas-Components,SilverTeamWork/Silverpeas-Components,SilverYoCha/Silverpeas-Components,ebonnet/Silverpeas-Components,Silverpeas/Silverpeas-Components,SilverTeamWork/Silverpeas-Components,SilverYoCha/Silverpeas-Components,ebonnet/Silverpeas-Components,ebonnet/Silverpeas-Components,Silverpeas/Silverpeas-Components,auroreallibe/Silverpeas-Components,SilverYoCha/Silverpeas-Components,mmoqui/Silverpeas-Components,ebonnet/Silverpeas-Components,Silverpeas/Silverpeas-Components,mmoqui/Silverpeas-Components,ebonnet/Silverpeas-Components,auroreallibe/Silverpeas-Components,auroreallibe/Silverpeas-Components,mmoqui/Silverpeas-Components,ebonnet/Silverpeas-Components,ebonnet/Silverpeas-Components | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have recieved a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.gallery.socialNetwork;
/**
* SocialGallery is the class representing the events of the gallery
*
*
* @author bourakbi
* @see SocialInformation
* @see SocialInformationGallery
*
*/
import com.silverpeas.calendar.Date;
import com.silverpeas.gallery.control.ejb.GalleryBm;
import com.silverpeas.socialnetwork.model.SocialInformation;
import com.silverpeas.socialnetwork.provider.SocialGalleryInterface;
import com.stratelia.webactiv.beans.admin.ComponentInstLight;
import org.silverpeas.core.admin.OrganizationControllerProvider;
import org.silverpeas.date.Period;
import org.silverpeas.util.EJBUtilitaire;
import org.silverpeas.util.JNDINames;
import org.silverpeas.util.exception.SilverpeasException;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SocialGallery implements SocialGalleryInterface {
protected SocialGallery() {
}
/**
* get the my SocialInformationGallery according to number of Item and the first Index
*
* @param userId
* @param begin
* @param end
* @return List<SocialInformationGallery>
*/
@Override
public List<SocialInformation> getSocialInformationsList(String userId, Date begin, Date end) {
return getGalleryBm().getAllMediaByUserId(userId, Period.from(begin, end));
}
/**
* get the SocialInformationGallery of my contatcs according to number of Item and the first Index
*
* @param myId
* @param myContactsIds
* @param begin
* @param end
* @return List
* @throws SilverpeasException
*/
@Override
public List<SocialInformation> getSocialInformationsListOfMyContacts(String myId,
List<String> myContactsIds, Date begin, Date end) throws SilverpeasException {
List<SocialInformation> listSocialInfo = new ArrayList<SocialInformation>();
List<String> listComponents = this.getListAvailable(myId);
if(listComponents != null && listComponents.size() > 0) {
listSocialInfo = getGalleryBm().getSocialInformationListOfMyContacts(myContactsIds, listComponents, Period.from(begin, end));
}
return listSocialInfo;
}
private GalleryBm getGalleryBm() {
return EJBUtilitaire.getEJBObjectRef(JNDINames.GALLERYBM_EJBHOME, GalleryBm.class);
}
/**
* gets the available component for a given users list
*
* @param userId
* @return List<String>
*/
private List<String> getListAvailable(String userId) {
List<ComponentInstLight> availableList = OrganizationControllerProvider.
getOrganisationController().getAvailComponentInstLights(userId, "gallery");
List<String> idsList = new ArrayList<String>(availableList.size());
for (ComponentInstLight comp : availableList) {
idsList.add(comp.getId());
}
return idsList;
}
}
| gallery/gallery-ejb/src/main/java/com/silverpeas/gallery/socialNetwork/SocialGallery.java | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have recieved a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.gallery.socialNetwork;
/**
* SocialGallery is the class representing the events of the gallery
*
*
* @author bourakbi
* @see SocialInformation
* @see SocialInformationGallery
*
*/
import com.silverpeas.calendar.Date;
import com.silverpeas.gallery.control.ejb.GalleryBm;
import com.silverpeas.socialnetwork.model.SocialInformation;
import com.silverpeas.socialnetwork.provider.SocialGalleryInterface;
import com.stratelia.webactiv.beans.admin.ComponentInstLight;
import org.silverpeas.core.admin.OrganizationControllerProvider;
import org.silverpeas.util.EJBUtilitaire;
import org.silverpeas.util.JNDINames;
import org.silverpeas.util.exception.SilverpeasException;
import org.silverpeas.date.Period;
import java.util.ArrayList;
import java.util.List;
public class SocialGallery implements SocialGalleryInterface {
/**
* get the my SocialInformationGallery according to number of Item and the first Index
*
* @param userId
* @param begin
* @param end
* @return List<SocialInformationGallery>
*/
@Override
public List<SocialInformation> getSocialInformationsList(String userId, Date begin, Date end) {
return getGalleryBm().getAllMediaByUserId(userId, Period.from(begin, end));
}
/**
* get the SocialInformationGallery of my contatcs according to number of Item and the first Index
*
* @param myId
* @param myContactsIds
* @param begin
* @param end
* @return List
* @throws SilverpeasException
*/
@Override
public List<SocialInformation> getSocialInformationsListOfMyContacts(String myId,
List<String> myContactsIds, Date begin, Date end) throws SilverpeasException {
List<SocialInformation> listSocialInfo = new ArrayList<SocialInformation>();
List<String> listComponents = this.getListAvailable(myId);
if(listComponents != null && listComponents.size() > 0) {
listSocialInfo = getGalleryBm().getSocialInformationListOfMyContacts(myContactsIds, listComponents, Period.from(begin, end));
}
return listSocialInfo;
}
private GalleryBm getGalleryBm() {
return EJBUtilitaire.getEJBObjectRef(JNDINames.GALLERYBM_EJBHOME, GalleryBm.class);
}
/**
* gets the available component for a given users list
*
* @param userId
* @return List<String>
*/
private List<String> getListAvailable(String userId) {
List<ComponentInstLight> availableList = OrganizationControllerProvider.
getOrganisationController().getAvailComponentInstLights(userId, "gallery");
List<String> idsList = new ArrayList<String>(availableList.size());
for (ComponentInstLight comp : availableList) {
idsList.add(comp.getId());
}
return idsList;
}
}
| Take into account some parts of the social network are now managed by CDI
| gallery/gallery-ejb/src/main/java/com/silverpeas/gallery/socialNetwork/SocialGallery.java | Take into account some parts of the social network are now managed by CDI | <ide><path>allery/gallery-ejb/src/main/java/com/silverpeas/gallery/socialNetwork/SocialGallery.java
<ide> import com.silverpeas.socialnetwork.provider.SocialGalleryInterface;
<ide> import com.stratelia.webactiv.beans.admin.ComponentInstLight;
<ide> import org.silverpeas.core.admin.OrganizationControllerProvider;
<add>import org.silverpeas.date.Period;
<ide> import org.silverpeas.util.EJBUtilitaire;
<ide> import org.silverpeas.util.JNDINames;
<ide> import org.silverpeas.util.exception.SilverpeasException;
<del>import org.silverpeas.date.Period;
<ide>
<add>import javax.inject.Singleton;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>@Singleton
<ide> public class SocialGallery implements SocialGalleryInterface {
<add>
<add> protected SocialGallery() {
<add> }
<ide>
<ide> /**
<ide> * get the my SocialInformationGallery according to number of Item and the first Index |
|
Java | apache-2.0 | d1c7c993abb336ab46a677af7f780f7aec9218db | 0 | mattprecious/smstimefix,mattprecious/smstimefix,mattprecious/smstimefix | /*
* Copyright 2011 Matthew Precious
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mattprecious.smsfix.library;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences settings = context.getSharedPreferences(context.getPackageName() + "_preferences", 0);
if (settings.getBoolean("active", false)) {
Intent svc = new Intent(context, FixService.class);
context.startService(svc);
}
}
} | SMSFixLibrary/src/com/mattprecious/smsfix/library/Receiver.java | /*
* Copyright 2011 Matthew Precious
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mattprecious.smsfix.library;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (settings.getBoolean("active", false)) {
Intent svc = new Intent(context, FixService.class);
context.startService(svc);
}
}
} | Attempt to fix start-on-boot issues. | SMSFixLibrary/src/com/mattprecious/smsfix/library/Receiver.java | Attempt to fix start-on-boot issues. | <ide><path>MSFixLibrary/src/com/mattprecious/smsfix/library/Receiver.java
<ide> import android.content.Intent;
<ide> import android.content.SharedPreferences;
<ide> import android.preference.PreferenceManager;
<add>import android.util.Log;
<ide>
<ide> public class Receiver extends BroadcastReceiver {
<ide>
<ide> @Override
<ide> public void onReceive(Context context, Intent intent) {
<del> SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
<add> SharedPreferences settings = context.getSharedPreferences(context.getPackageName() + "_preferences", 0);
<ide>
<ide> if (settings.getBoolean("active", false)) {
<ide> Intent svc = new Intent(context, FixService.class); |
|
Java | mit | d3255f03a1233c7392f4d3c991c24a8e655d199d | 0 | CS2103JAN2017-T09-B4/main,CS2103JAN2017-T09-B4/main,CS2103JAN2017-T09-B4/main | package seedu.tache.model;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import edu.emory.mathcs.backport.java.util.Collections;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import seedu.tache.commons.core.ComponentManager;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.core.UnmodifiableObservableList;
import seedu.tache.commons.events.model.TaskManagerChangedEvent;
import seedu.tache.commons.events.ui.FilteredTaskListUpdatedEvent;
import seedu.tache.commons.events.ui.PopulateRecurringGhostTaskEvent;
import seedu.tache.commons.events.ui.TaskListTypeChangedEvent;
import seedu.tache.commons.events.ui.TaskPanelConnectionChangedEvent;
import seedu.tache.commons.util.CollectionUtil;
import seedu.tache.commons.util.StringUtil;
import seedu.tache.model.tag.Tag;
import seedu.tache.model.task.DateTime;
import seedu.tache.model.task.ReadOnlyTask;
import seedu.tache.model.task.Task;
import seedu.tache.model.task.UniqueTaskList;
import seedu.tache.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.tache.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the task manager data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
//@@author A0139925U
public static final int MARGIN_OF_ERROR = 1;
//@@author A0142255M
public static final String TASK_LIST_TYPE_ALL = "All Tasks";
public static final String TASK_LIST_TYPE_COMPLETED = "Completed Tasks";
public static final String TASK_LIST_TYPE_UNCOMPLETED = "Uncompleted Tasks";
public static final String TASK_LIST_TYPE_TIMED = "Timed Tasks";
public static final String TASK_LIST_TYPE_FLOATING = "Floating Tasks";
//@@author A0139925U
public static final String TASK_LIST_TYPE_FOUND = "Found Tasks";
//@@author A0139961U
public static final String TASK_LIST_TYPE_DUE_TODAY = "Tasks Due Today";
public static final String TASK_LIST_TYPE_DUE_THIS_WEEK = "Tasks Due This Week";
public static final String TASK_LIST_TYPE_OVERDUE = "Overdue Tasks";
//@@author
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
//@@author A0139925U
private final TaskManager taskManager;
private final FilteredList<ReadOnlyTask> filteredTasks;
private Set<String> latestKeywords;
//@@author A0142255M
private String filteredTaskListType = TASK_LIST_TYPE_ALL;
//@@author
/**
* Initializes a ModelManager with the given taskManager and userPrefs.
*/
public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(taskManager, userPrefs);
logger.fine("Initializing with task manager: " + taskManager + " and user prefs " + userPrefs);
this.taskManager = new TaskManager(taskManager);
filteredTasks = new FilteredList<>(this.taskManager.getTaskList());
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
//@@author A0142255M
@Override
public void resetData(ReadOnlyTaskManager newData) {
assert newData != null;
taskManager.resetData(newData);
updateFilteredListToShowAll();
updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
indicateTaskManagerChanged();
}
//@@author
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
//@@author A0142255M
/**
* Raises events to indicate that the model has changed.
*/
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
raise(new PopulateRecurringGhostTaskEvent(getAllRecurringGhostTasks()));
}
//@@author
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
//@@author A0142255M
@Override
public synchronized void addTask(Task task) throws DuplicateTaskException {
assert task != null;
taskManager.addTask(task);
indicateTaskManagerChanged();
}
//@@author A0150120H
@Override
public synchronized void addTask(int index, Task task) throws DuplicateTaskException {
taskManager.addTask(index, task);
indicateTaskManagerChanged();
}
//@@author
@Override
public void updateTask(ReadOnlyTask taskToUpdate, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
taskManager.updateTask(taskToUpdate, editedTask);
indicateTaskManagerChanged();
}
//=========== Filtered Task List Accessors =============================================================
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
ObservableList<ReadOnlyTask> filteredTasksWithRecurringTasks = populateUncompletedRecurringDatesAsTask();
raise(new TaskPanelConnectionChangedEvent(filteredTasksWithRecurringTasks));
return new UnmodifiableObservableList<>(filteredTasksWithRecurringTasks);
}
//@@author A0142255M
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
}
//@@author A0139925U
@Override
public void updateFilteredListToShowUncompleted() {
updateFilteredTaskList(new PredicateExpression(new ActiveQualifier(true)));
updateFilteredTaskListType(TASK_LIST_TYPE_UNCOMPLETED);
}
@Override
public void updateFilteredListToShowCompleted() {
updateFilteredTaskList(new PredicateExpression(new ActiveQualifier(false)));
updateFilteredTaskListType(TASK_LIST_TYPE_COMPLETED);
}
//@@author A0142255M
@Override
public void updateFilteredListToShowTimed() {
updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(true)));
updateFilteredTaskListType(TASK_LIST_TYPE_TIMED);
}
@Override
public void updateFilteredListToShowFloating() {
updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(false)));
updateFilteredTaskListType(TASK_LIST_TYPE_FLOATING);
}
//@@author A0139961U
@Override
public void updateFilteredListToShowDueToday() {
updateFilteredTaskListType(TASK_LIST_TYPE_DUE_TODAY);
updateFilteredTaskList(new PredicateExpression(new DueTodayQualifier(true)));
}
public void updateFilteredListToShowDueThisWeek() {
updateFilteredTaskListType(TASK_LIST_TYPE_DUE_THIS_WEEK);
updateFilteredTaskList(new PredicateExpression(new DueThisWeekQualifier(true)));
}
public void updateFilteredListToShowOverdueTasks() {
updateFilteredTaskListType(TASK_LIST_TYPE_OVERDUE);
updateFilteredTaskList(new PredicateExpression(new OverdueQualifier()));
}
//@@author A0142255M
/**
* Provides functionality for find command and raises TaskListTypeChangedEvent to update UI.
* Set<String> is converted to ArrayList<String> so that String can be retrieved.
*/
@Override
public void updateFilteredTaskList(Set<String> keywords) {
assert keywords != null;
updateFilteredTaskList(new PredicateExpression(new MultiQualifier(keywords)));
ArrayList<String> keywordsList = new ArrayList<String>(keywords);
updateFilteredTaskListType(TASK_LIST_TYPE_FOUND);
retainLatestKeywords(keywords);
raise(new TaskListTypeChangedEvent("Find \"" + keywordsList.get(0) + "\""));
}
private void updateFilteredTaskList(Expression expression) {
assert expression != null;
filteredTasks.setPredicate(expression::satisfies);
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
}
@Override
public String getFilteredTaskListType() {
return filteredTaskListType;
}
private void updateFilteredTaskListType(String newFilteredTaskListType) {
assert newFilteredTaskListType != null;
assert !newFilteredTaskListType.equals("");
if (!filteredTaskListType.equals(newFilteredTaskListType)) {
raise(new TaskListTypeChangedEvent(newFilteredTaskListType));
}
filteredTaskListType = newFilteredTaskListType;
}
//@@author A0139925U
private void retainLatestKeywords(Set<String> keywords) {
latestKeywords = keywords;
}
public void updateCurrentFilteredList() {
switch(filteredTaskListType) {
case TASK_LIST_TYPE_ALL:
updateFilteredListToShowAll();
break;
case TASK_LIST_TYPE_COMPLETED:
updateFilteredListToShowCompleted();
break;
case TASK_LIST_TYPE_UNCOMPLETED:
updateFilteredListToShowUncompleted();
break;
case TASK_LIST_TYPE_TIMED:
updateFilteredListToShowTimed();
break;
case TASK_LIST_TYPE_FLOATING:
updateFilteredListToShowFloating();
break;
case TASK_LIST_TYPE_FOUND:
updateFilteredTaskList(latestKeywords);
break;
case TASK_LIST_TYPE_DUE_TODAY:
updateFilteredListToShowDueToday();
break;
case TASK_LIST_TYPE_DUE_THIS_WEEK:
updateFilteredListToShowDueThisWeek();
break;
default:
}
}
//@@author
//========== Inner classes/interfaces/methods used for filtering =================================================
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
//@@author A0139925U
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
String[] nameElements = task.getName().fullName.split(" ");
boolean partialMatch = false;
//Remove square brackets
String trimmedNameKeywords = nameKeyWords.toString()
.substring(1, nameKeyWords.toString().length() - 1).toLowerCase();
for (int i = 0; i < nameElements.length; i++) {
if (computeLevenshteinDistance(trimmedNameKeywords, nameElements[i].toLowerCase()) <= MARGIN_OF_ERROR) {
partialMatch = true;
break;
}
}
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent()
|| partialMatch;
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
//@@author
//@@author A0142255M
private class TimedQualifier implements Qualifier {
private boolean isTimed;
TimedQualifier(boolean isTimed) {
this.isTimed = isTimed;
}
@Override
public boolean run(ReadOnlyTask task) {
assert task != null;
if (isTimed) {
return task.getTimedStatus();
} else {
return !task.getTimedStatus();
}
}
@Override
public String toString() {
return "timed=" + isTimed;
}
}
//@@author A0139925U
private class ActiveQualifier implements Qualifier {
private boolean isActive;
ActiveQualifier(boolean isActive) {
this.isActive = isActive;
}
@Override
public boolean run(ReadOnlyTask task) {
if (isActive) {
return task.getActiveStatus();
} else {
return !task.getActiveStatus();
}
}
@Override
public String toString() {
return "active=" + isActive;
}
}
//@@author A0139961U
private class DueTodayQualifier implements Qualifier {
private boolean isDueToday;
DueTodayQualifier(boolean isDueToday) {
this.isDueToday = isDueToday;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && isDueToday) {
if (task.getStartDateTime().isPresent()) {
return task.isWithinDate(DateTime.removeTime(new Date()));
}
return task.getEndDateTime().get().isToday();
} else {
return false;
}
}
@Override
public String toString() {
return "dueToday=true";
}
}
private class DueThisWeekQualifier implements Qualifier {
private boolean isDueThisWeek;
DueThisWeekQualifier(boolean isDueThisWeek) {
this.isDueThisWeek = isDueThisWeek;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && isDueThisWeek) {
return task.getEndDateTime().get().isSameWeek();
} else {
return false;
}
}
@Override
public String toString() {
return "dueThisWeek=true";
}
}
private class OverdueQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && task.getActiveStatus()) {
return task.getEndDateTime().get().hasPassed();
} else {
return false;
}
}
@Override
public String toString() {
return "dueThisWeek=true";
}
}
//@@author A0139925U
private class DateTimeQualifier implements Qualifier {
private Set<String> dateTimeKeyWords;
DateTimeQualifier(Set<String> dateTimeKeyWords) {
this.dateTimeKeyWords = dateTimeKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getStartDateTime().isPresent()) {
for (int i = 0; i < dateTimeKeyWords.size(); i++) {
if (dateTimeKeyWords.toArray()[i].equals(task.getStartDateTime().get().getDateOnly()) ||
dateTimeKeyWords.toArray()[i].equals(task.getStartDateTime().get().getTimeOnly())) {
return true;
}
}
}
if (task.getEndDateTime().isPresent()) {
for (int i = 0; i < dateTimeKeyWords.size(); i++) {
if (dateTimeKeyWords.toArray()[i].equals(task.getEndDateTime().get().getDateOnly()) ||
dateTimeKeyWords.toArray()[i].equals(task.getEndDateTime().get().getTimeOnly())) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return "datetime=" + String.join(", ", dateTimeKeyWords);
}
}
private class MultiQualifier implements Qualifier {
private Set<String> multiKeyWords;
private NameQualifier nameQualifier;
private DateTimeQualifier dateTimeQualifier;
private ActiveQualifier activeQualifier;
private TagQualifier tagQualifier;
MultiQualifier(Set<String> multiKeyWords) {
this.multiKeyWords = multiKeyWords;
nameQualifier = new NameQualifier(multiKeyWords);
dateTimeQualifier = new DateTimeQualifier(multiKeyWords);
activeQualifier = new ActiveQualifier(true);
tagQualifier = new TagQualifier(multiKeyWords);
}
@Override
public boolean run(ReadOnlyTask task) {
return (nameQualifier.run(task) || dateTimeQualifier.run(task)
|| tagQualifier.run(task)) && activeQualifier.run(task);
}
@Override
public String toString() {
return "multi=" + String.join(", ", multiKeyWords);
}
}
private class TagQualifier implements Qualifier {
private Set<String> tagKeywords;
TagQualifier(Set<String> tagKeywords) {
this.tagKeywords = tagKeywords;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getTags().toSet().size() != 0) {
Set<Tag> tagElements = (Set<Tag>) task.getTags().toSet();
boolean validMatch = false;
//Remove square brackets
String trimmedTagKeywords = tagKeywords.toString()
.substring(1, tagKeywords.toString().length() - 1).toLowerCase();
for (Tag tag: tagElements) {
if (computeLevenshteinDistance(trimmedTagKeywords, tag.tagName.toLowerCase())
<= MARGIN_OF_ERROR) {
validMatch = true;
break;
}
}
return validMatch;
}
return false;
}
@Override
public String toString() {
return "tag=" + String.join(", ", tagKeywords);
}
}
private class ActiveTimedQualifier implements Qualifier {
private TimedQualifier timedQualifier;
private ActiveQualifier activeQualifier;
ActiveTimedQualifier(boolean isTimed) {
timedQualifier = new TimedQualifier(isTimed);
activeQualifier = new ActiveQualifier(true);
}
@Override
public boolean run(ReadOnlyTask task) {
return timedQualifier.run(task) && activeQualifier.run(task);
}
@Override
public String toString() {
return "activetimed";
}
}
private int computeLevenshteinDistance(CharSequence str1, CharSequence str2) {
int[][] distance = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
distance[i][0] = i;
}
for (int j = 1; j <= str2.length(); j++) {
distance[0][j] = j;
}
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
distance[i][j] =
minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1] +
((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));
}
}
return distance[str1.length()][str2.length()];
}
private int minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
private ObservableList<ReadOnlyTask> populateUncompletedRecurringDatesAsTask() {
List<ReadOnlyTask> concatenated = new ArrayList<>();
for (int i = 0; i < filteredTasks.size(); i++) {
if (filteredTasks.get(i).getRecurringStatus()) {
if (filteredTaskListType.equals(TASK_LIST_TYPE_DUE_TODAY)) {
Collections.addAll(concatenated, filteredTasks.get(i)
.getUncompletedRecurList(new Date()).toArray());
} else if (filteredTaskListType.equals(TASK_LIST_TYPE_DUE_TODAY)) {
Calendar dateThisWeek = Calendar.getInstance();
dateThisWeek.setTime(new Date());
dateThisWeek.add(Calendar.WEEK_OF_YEAR, 1);
Collections.addAll(concatenated, filteredTasks.get(i)
.getUncompletedRecurList(dateThisWeek.getTime()).toArray());
} else {
Collections.addAll(concatenated, filteredTasks.get(i).getUncompletedRecurList(null).toArray());
}
}
}
Collections.addAll(concatenated, filteredTasks.toArray());
return FXCollections.observableList(concatenated);
}
public ObservableList<ReadOnlyTask> getAllRecurringGhostTasks() {
List<ReadOnlyTask> concatenated = new ArrayList<>();
for (int i = 0; i < taskManager.getTaskList().size(); i++) {
if (taskManager.getTaskList().get(i).getRecurringStatus()) {
Collections.addAll(concatenated, taskManager.getTaskList().get(i)
.getUncompletedRecurList(null).toArray());
}
}
return FXCollections.observableList(concatenated);
}
//@@author A0150120H
@Override
public int getFilteredTaskListIndex(ReadOnlyTask targetTask) {
return getFilteredTaskList().indexOf(targetTask);
}
}
| src/main/java/seedu/tache/model/ModelManager.java | package seedu.tache.model;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import edu.emory.mathcs.backport.java.util.Collections;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import seedu.tache.commons.core.ComponentManager;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.core.UnmodifiableObservableList;
import seedu.tache.commons.events.model.TaskManagerChangedEvent;
import seedu.tache.commons.events.ui.FilteredTaskListUpdatedEvent;
import seedu.tache.commons.events.ui.PopulateRecurringGhostTaskEvent;
import seedu.tache.commons.events.ui.TaskListTypeChangedEvent;
import seedu.tache.commons.events.ui.TaskPanelConnectionChangedEvent;
import seedu.tache.commons.util.CollectionUtil;
import seedu.tache.commons.util.StringUtil;
import seedu.tache.model.task.DateTime;
import seedu.tache.model.task.ReadOnlyTask;
import seedu.tache.model.task.Task;
import seedu.tache.model.task.UniqueTaskList;
import seedu.tache.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.tache.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the task manager data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
//@@author A0139925U
public static final int MARGIN_OF_ERROR = 1;
//@@author A0142255M
public static final String TASK_LIST_TYPE_ALL = "All Tasks";
public static final String TASK_LIST_TYPE_COMPLETED = "Completed Tasks";
public static final String TASK_LIST_TYPE_UNCOMPLETED = "Uncompleted Tasks";
public static final String TASK_LIST_TYPE_TIMED = "Timed Tasks";
public static final String TASK_LIST_TYPE_FLOATING = "Floating Tasks";
//@@author A0139925U
public static final String TASK_LIST_TYPE_FOUND = "Found Tasks";
//@@author A0139961U
public static final String TASK_LIST_TYPE_DUE_TODAY = "Tasks Due Today";
public static final String TASK_LIST_TYPE_DUE_THIS_WEEK = "Tasks Due This Week";
public static final String TASK_LIST_TYPE_OVERDUE = "Overdue Tasks";
//@@author
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
//@@author A0139925U
private final TaskManager taskManager;
private final FilteredList<ReadOnlyTask> filteredTasks;
private Set<String> latestKeywords;
//@@author A0142255M
private String filteredTaskListType = TASK_LIST_TYPE_ALL;
//@@author
/**
* Initializes a ModelManager with the given taskManager and userPrefs.
*/
public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(taskManager, userPrefs);
logger.fine("Initializing with task manager: " + taskManager + " and user prefs " + userPrefs);
this.taskManager = new TaskManager(taskManager);
filteredTasks = new FilteredList<>(this.taskManager.getTaskList());
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
//@@author A0142255M
@Override
public void resetData(ReadOnlyTaskManager newData) {
assert newData != null;
taskManager.resetData(newData);
updateFilteredListToShowAll();
updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
indicateTaskManagerChanged();
}
//@@author
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
//@@author A0142255M
/**
* Raises events to indicate that the model has changed.
*/
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
raise(new PopulateRecurringGhostTaskEvent(getAllRecurringGhostTasks()));
}
//@@author
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
//@@author A0142255M
@Override
public synchronized void addTask(Task task) throws DuplicateTaskException {
assert task != null;
taskManager.addTask(task);
indicateTaskManagerChanged();
}
//@@author A0150120H
@Override
public synchronized void addTask(int index, Task task) throws DuplicateTaskException {
taskManager.addTask(index, task);
indicateTaskManagerChanged();
}
//@@author
@Override
public void updateTask(ReadOnlyTask taskToUpdate, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
taskManager.updateTask(taskToUpdate, editedTask);
indicateTaskManagerChanged();
}
//=========== Filtered Task List Accessors =============================================================
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
ObservableList<ReadOnlyTask> filteredTasksWithRecurringTasks = populateUncompletedRecurringDatesAsTask();
raise(new TaskPanelConnectionChangedEvent(filteredTasksWithRecurringTasks));
return new UnmodifiableObservableList<>(filteredTasksWithRecurringTasks);
}
//@@author A0142255M
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
updateFilteredTaskListType(TASK_LIST_TYPE_ALL);
}
//@@author A0139925U
@Override
public void updateFilteredListToShowUncompleted() {
updateFilteredTaskList(new PredicateExpression(new ActiveQualifier(true)));
updateFilteredTaskListType(TASK_LIST_TYPE_UNCOMPLETED);
}
@Override
public void updateFilteredListToShowCompleted() {
updateFilteredTaskList(new PredicateExpression(new ActiveQualifier(false)));
updateFilteredTaskListType(TASK_LIST_TYPE_COMPLETED);
}
//@@author A0142255M
@Override
public void updateFilteredListToShowTimed() {
updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(true)));
updateFilteredTaskListType(TASK_LIST_TYPE_TIMED);
}
@Override
public void updateFilteredListToShowFloating() {
updateFilteredTaskList(new PredicateExpression(new ActiveTimedQualifier(false)));
updateFilteredTaskListType(TASK_LIST_TYPE_FLOATING);
}
//@@author A0139961U
@Override
public void updateFilteredListToShowDueToday() {
updateFilteredTaskListType(TASK_LIST_TYPE_DUE_TODAY);
updateFilteredTaskList(new PredicateExpression(new DueTodayQualifier(true)));
}
public void updateFilteredListToShowDueThisWeek() {
updateFilteredTaskListType(TASK_LIST_TYPE_DUE_THIS_WEEK);
updateFilteredTaskList(new PredicateExpression(new DueThisWeekQualifier(true)));
}
public void updateFilteredListToShowOverdueTasks() {
updateFilteredTaskListType(TASK_LIST_TYPE_OVERDUE);
updateFilteredTaskList(new PredicateExpression(new OverdueQualifier()));
}
//@@author A0142255M
/**
* Provides functionality for find command and raises TaskListTypeChangedEvent to update UI.
* Set<String> is converted to ArrayList<String> so that String can be retrieved.
*/
@Override
public void updateFilteredTaskList(Set<String> keywords) {
assert keywords != null;
updateFilteredTaskList(new PredicateExpression(new MultiQualifier(keywords)));
ArrayList<String> keywordsList = new ArrayList<String>(keywords);
updateFilteredTaskListType(TASK_LIST_TYPE_FOUND);
retainLatestKeywords(keywords);
raise(new TaskListTypeChangedEvent("Find \"" + keywordsList.get(0) + "\""));
}
private void updateFilteredTaskList(Expression expression) {
assert expression != null;
filteredTasks.setPredicate(expression::satisfies);
raise(new FilteredTaskListUpdatedEvent(getFilteredTaskList()));
}
@Override
public String getFilteredTaskListType() {
return filteredTaskListType;
}
private void updateFilteredTaskListType(String newFilteredTaskListType) {
assert newFilteredTaskListType != null;
assert !newFilteredTaskListType.equals("");
if (!filteredTaskListType.equals(newFilteredTaskListType)) {
raise(new TaskListTypeChangedEvent(newFilteredTaskListType));
}
filteredTaskListType = newFilteredTaskListType;
}
//@@author A0139925U
private void retainLatestKeywords(Set<String> keywords) {
latestKeywords = keywords;
}
public void updateCurrentFilteredList() {
switch(filteredTaskListType) {
case TASK_LIST_TYPE_ALL:
updateFilteredListToShowAll();
break;
case TASK_LIST_TYPE_COMPLETED:
updateFilteredListToShowCompleted();
break;
case TASK_LIST_TYPE_UNCOMPLETED:
updateFilteredListToShowUncompleted();
break;
case TASK_LIST_TYPE_TIMED:
updateFilteredListToShowTimed();
break;
case TASK_LIST_TYPE_FLOATING:
updateFilteredListToShowFloating();
break;
case TASK_LIST_TYPE_FOUND:
updateFilteredTaskList(latestKeywords);
break;
case TASK_LIST_TYPE_DUE_TODAY:
updateFilteredListToShowDueToday();
break;
case TASK_LIST_TYPE_DUE_THIS_WEEK:
updateFilteredListToShowDueThisWeek();
break;
default:
}
}
//@@author
//========== Inner classes/interfaces/methods used for filtering =================================================
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
//@@author A0139925U
@Override
public boolean run(ReadOnlyTask task) {
String[] nameElements = task.getName().fullName.split(" ");
boolean partialMatch = false;
String trimmedNameKeyWords = nameKeyWords.toString()
.substring(1, nameKeyWords.toString().length() - 1).toLowerCase();
for (int i = 0; i < nameElements.length; i++) {
if (computeLevenshteinDistance(trimmedNameKeyWords, nameElements[i].toLowerCase()) <= MARGIN_OF_ERROR) {
partialMatch = true;
break;
}
}
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent()
|| partialMatch;
}
//@@author
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
//@@author A0142255M
private class TimedQualifier implements Qualifier {
private boolean isTimed;
TimedQualifier(boolean isTimed) {
this.isTimed = isTimed;
}
@Override
public boolean run(ReadOnlyTask task) {
assert task != null;
if (isTimed) {
return task.getTimedStatus();
} else {
return !task.getTimedStatus();
}
}
@Override
public String toString() {
return "timed=" + isTimed;
}
}
//@@author A0139925U
private class ActiveQualifier implements Qualifier {
private boolean isActive;
ActiveQualifier(boolean isActive) {
this.isActive = isActive;
}
@Override
public boolean run(ReadOnlyTask task) {
if (isActive) {
return task.getActiveStatus();
} else {
return !task.getActiveStatus();
}
}
@Override
public String toString() {
return "active=" + isActive;
}
}
//@@author A0139961U
private class DueTodayQualifier implements Qualifier {
private boolean isDueToday;
DueTodayQualifier(boolean isDueToday) {
this.isDueToday = isDueToday;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && isDueToday) {
if (task.getStartDateTime().isPresent()) {
return task.isWithinDate(DateTime.removeTime(new Date()));
}
return task.getEndDateTime().get().isToday();
} else {
return false;
}
}
@Override
public String toString() {
return "dueToday=true";
}
}
private class DueThisWeekQualifier implements Qualifier {
private boolean isDueThisWeek;
DueThisWeekQualifier(boolean isDueThisWeek) {
this.isDueThisWeek = isDueThisWeek;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && isDueThisWeek) {
return task.getEndDateTime().get().isSameWeek();
} else {
return false;
}
}
@Override
public String toString() {
return "dueThisWeek=true";
}
}
private class OverdueQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask task) {
if (task.getEndDateTime().isPresent() && task.getActiveStatus()) {
return task.getEndDateTime().get().hasPassed();
} else {
return false;
}
}
@Override
public String toString() {
return "dueThisWeek=true";
}
}
//@@author A0139925U
private class DateTimeQualifier implements Qualifier {
private Set<String> dateTimeKeyWords;
DateTimeQualifier(Set<String> dateTimeKeyWords) {
this.dateTimeKeyWords = dateTimeKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
if (task.getStartDateTime().isPresent()) {
for (int i = 0; i < dateTimeKeyWords.size(); i++) {
if (dateTimeKeyWords.toArray()[i].equals(task.getStartDateTime().get().getDateOnly()) ||
dateTimeKeyWords.toArray()[i].equals(task.getStartDateTime().get().getTimeOnly())) {
return true;
}
}
}
if (task.getEndDateTime().isPresent()) {
for (int i = 0; i < dateTimeKeyWords.size(); i++) {
if (dateTimeKeyWords.toArray()[i].equals(task.getEndDateTime().get().getDateOnly()) ||
dateTimeKeyWords.toArray()[i].equals(task.getEndDateTime().get().getTimeOnly())) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return "datetime=" + String.join(", ", dateTimeKeyWords);
}
}
private class MultiQualifier implements Qualifier {
private Set<String> multiKeyWords;
private NameQualifier nameQualifier;
private DateTimeQualifier dateTimeQualifier;
private ActiveQualifier activeQualifier;
MultiQualifier(Set<String> multiKeyWords) {
this.multiKeyWords = multiKeyWords;
nameQualifier = new NameQualifier(multiKeyWords);
dateTimeQualifier = new DateTimeQualifier(multiKeyWords);
activeQualifier = new ActiveQualifier(true);
}
@Override
public boolean run(ReadOnlyTask task) {
return (nameQualifier.run(task) || dateTimeQualifier.run(task)) && activeQualifier.run(task);
}
@Override
public String toString() {
return "multi=" + String.join(", ", multiKeyWords);
}
}
private class ActiveTimedQualifier implements Qualifier {
private TimedQualifier timedQualifier;
private ActiveQualifier activeQualifier;
ActiveTimedQualifier(boolean isTimed) {
timedQualifier = new TimedQualifier(isTimed);
activeQualifier = new ActiveQualifier(true);
}
@Override
public boolean run(ReadOnlyTask task) {
return timedQualifier.run(task) && activeQualifier.run(task);
}
@Override
public String toString() {
return "activetimed";
}
}
private int computeLevenshteinDistance(CharSequence str1, CharSequence str2) {
int[][] distance = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
distance[i][0] = i;
}
for (int j = 1; j <= str2.length(); j++) {
distance[0][j] = j;
}
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
distance[i][j] =
minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1] +
((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));
}
}
return distance[str1.length()][str2.length()];
}
private int minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
private ObservableList<ReadOnlyTask> populateUncompletedRecurringDatesAsTask() {
List<ReadOnlyTask> concatenated = new ArrayList<>();
for (int i = 0; i < filteredTasks.size(); i++) {
if (filteredTasks.get(i).getRecurringStatus()) {
if (filteredTaskListType.equals(TASK_LIST_TYPE_DUE_TODAY)) {
Collections.addAll(concatenated, filteredTasks.get(i)
.getUncompletedRecurList(new Date()).toArray());
} else if (filteredTaskListType.equals(TASK_LIST_TYPE_DUE_TODAY)) {
Calendar dateThisWeek = Calendar.getInstance();
dateThisWeek.setTime(new Date());
dateThisWeek.add(Calendar.WEEK_OF_YEAR, 1);
Collections.addAll(concatenated, filteredTasks.get(i)
.getUncompletedRecurList(dateThisWeek.getTime()).toArray());
} else {
Collections.addAll(concatenated, filteredTasks.get(i).getUncompletedRecurList(null).toArray());
}
}
}
Collections.addAll(concatenated, filteredTasks.toArray());
return FXCollections.observableList(concatenated);
}
public ObservableList<ReadOnlyTask> getAllRecurringGhostTasks() {
List<ReadOnlyTask> concatenated = new ArrayList<>();
for (int i = 0; i < taskManager.getTaskList().size(); i++) {
if (taskManager.getTaskList().get(i).getRecurringStatus()) {
Collections.addAll(concatenated, taskManager.getTaskList().get(i)
.getUncompletedRecurList(null).toArray());
}
}
return FXCollections.observableList(concatenated);
}
//@@author A0150120H
@Override
public int getFilteredTaskListIndex(ReadOnlyTask targetTask) {
return getFilteredTaskList().indexOf(targetTask);
}
}
| Added TagQualifier and support for finding tags (including margin of error)
| src/main/java/seedu/tache/model/ModelManager.java | Added TagQualifier and support for finding tags (including margin of error) | <ide><path>rc/main/java/seedu/tache/model/ModelManager.java
<ide> import seedu.tache.commons.events.ui.TaskPanelConnectionChangedEvent;
<ide> import seedu.tache.commons.util.CollectionUtil;
<ide> import seedu.tache.commons.util.StringUtil;
<add>import seedu.tache.model.tag.Tag;
<ide> import seedu.tache.model.task.DateTime;
<ide> import seedu.tache.model.task.ReadOnlyTask;
<ide> import seedu.tache.model.task.Task;
<ide> boolean run(ReadOnlyTask task);
<ide> String toString();
<ide> }
<del>
<add> //@@author A0139925U
<ide> private class NameQualifier implements Qualifier {
<ide> private Set<String> nameKeyWords;
<ide>
<ide> NameQualifier(Set<String> nameKeyWords) {
<ide> this.nameKeyWords = nameKeyWords;
<ide> }
<del> //@@author A0139925U
<add>
<ide> @Override
<ide> public boolean run(ReadOnlyTask task) {
<ide> String[] nameElements = task.getName().fullName.split(" ");
<ide> boolean partialMatch = false;
<del> String trimmedNameKeyWords = nameKeyWords.toString()
<add> //Remove square brackets
<add> String trimmedNameKeywords = nameKeyWords.toString()
<ide> .substring(1, nameKeyWords.toString().length() - 1).toLowerCase();
<ide> for (int i = 0; i < nameElements.length; i++) {
<del> if (computeLevenshteinDistance(trimmedNameKeyWords, nameElements[i].toLowerCase()) <= MARGIN_OF_ERROR) {
<add> if (computeLevenshteinDistance(trimmedNameKeywords, nameElements[i].toLowerCase()) <= MARGIN_OF_ERROR) {
<ide> partialMatch = true;
<ide> break;
<ide> }
<ide> .isPresent()
<ide> || partialMatch;
<ide> }
<del> //@@author
<add>
<ide> @Override
<ide> public String toString() {
<ide> return "name=" + String.join(", ", nameKeyWords);
<ide> }
<ide> }
<del>
<add> //@@author
<ide> //@@author A0142255M
<ide> private class TimedQualifier implements Qualifier {
<ide> private boolean isTimed;
<ide> private NameQualifier nameQualifier;
<ide> private DateTimeQualifier dateTimeQualifier;
<ide> private ActiveQualifier activeQualifier;
<add> private TagQualifier tagQualifier;
<ide>
<ide> MultiQualifier(Set<String> multiKeyWords) {
<ide> this.multiKeyWords = multiKeyWords;
<ide> nameQualifier = new NameQualifier(multiKeyWords);
<ide> dateTimeQualifier = new DateTimeQualifier(multiKeyWords);
<ide> activeQualifier = new ActiveQualifier(true);
<del> }
<del>
<del> @Override
<del> public boolean run(ReadOnlyTask task) {
<del> return (nameQualifier.run(task) || dateTimeQualifier.run(task)) && activeQualifier.run(task);
<add> tagQualifier = new TagQualifier(multiKeyWords);
<add> }
<add>
<add> @Override
<add> public boolean run(ReadOnlyTask task) {
<add> return (nameQualifier.run(task) || dateTimeQualifier.run(task)
<add> || tagQualifier.run(task)) && activeQualifier.run(task);
<ide> }
<ide>
<ide> @Override
<ide> return "multi=" + String.join(", ", multiKeyWords);
<ide> }
<ide>
<add> }
<add>
<add> private class TagQualifier implements Qualifier {
<add> private Set<String> tagKeywords;
<add>
<add> TagQualifier(Set<String> tagKeywords) {
<add> this.tagKeywords = tagKeywords;
<add> }
<add>
<add> @Override
<add> public boolean run(ReadOnlyTask task) {
<add> if (task.getTags().toSet().size() != 0) {
<add> Set<Tag> tagElements = (Set<Tag>) task.getTags().toSet();
<add> boolean validMatch = false;
<add> //Remove square brackets
<add> String trimmedTagKeywords = tagKeywords.toString()
<add> .substring(1, tagKeywords.toString().length() - 1).toLowerCase();
<add> for (Tag tag: tagElements) {
<add> if (computeLevenshteinDistance(trimmedTagKeywords, tag.tagName.toLowerCase())
<add> <= MARGIN_OF_ERROR) {
<add> validMatch = true;
<add> break;
<add> }
<add> }
<add> return validMatch;
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return "tag=" + String.join(", ", tagKeywords);
<add> }
<ide> }
<ide>
<ide> private class ActiveTimedQualifier implements Qualifier { |
|
JavaScript | mit | b4a822236629bc1d431ebd6da924db759c197bfd | 0 | startxfr/jquery-mobile,hinaloe/jqm-demo-ja,arschmitz/jquery-mobile,startxfr/jquery-mobile,npmcomponent/cbou-jquery-mobile,hinaloe/jqm-demo-ja,hinaloe/jqm-demo-ja,arschmitz/uglymongrel-jquery-mobile,rwaldron/jquery-mobile,startxfr/jquery-mobile,arschmitz/jquery-mobile,rwaldron/jquery-mobile,npmcomponent/cbou-jquery-mobile,arschmitz/uglymongrel-jquery-mobile,arschmitz/uglymongrel-jquery-mobile,arschmitz/jquery-mobile,npmcomponent/cbou-jquery-mobile | /*
* jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt,
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {
//define vars for interal use
var $window = $(window),
$html = $('html'),
$head = $('head'),
//url path helpers for use in relative url management
path = {
//get path from current hash, or from a file path
get: function( newPath ){
if( newPath === undefined ){
newPath = location.hash;
}
return path.stripHash( newPath ).replace(/[^\/]*\.[^\/*]+$/, '');
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ){
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ){
location.hash = path;
},
//location pathname from intial directory request
origin: '',
setOrigin: function(){
path.origin = path.get( location.protocol + '//' + location.host + location.pathname );
},
//prefix a relative url with the current path
makeAbsolute: function( url ){
return path.get() + url;
},
//return a url path with the window's location protocol/hostname removed
clean: function( url ){
return url.replace( location.protocol + "//" + location.host, "");
},
//just return the url without an initial #
stripHash: function( url ){
return url.replace( /^#/, "" );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ){
return path.hasProtocol( path.clean( url ) );
},
hasProtocol: function( url ){
return (/^(:?\w+:)/).test( url );
},
//check if the url is relative
isRelative: function( url ){
return (/^[^\/|#]/).test( url ) && !path.hasProtocol( url );
},
isEmbeddedPage: function( url ){
return (/^#/).test( url );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
//array of pages that are visited during a single page load. each has a url and optional transition
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function(){
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function(){
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function(){
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition ){
//if there's forward history, wipe it
if( urlHistory.getNext() ){
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function(){
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
//disable hashchange event listener internally to ignore one change
//toggled internally when location.hash is updated to match the url of a successful page load
ignoreNextHashChange: true
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//contains role for next page, if defined on clicked link via data-rel
nextPageRole = null,
//queue to hold simultanious page transitions
pageTransitionQueue = [],
// indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children("base"),
hostURL = location.protocol + '//' + location.host,
docLocation = path.get( hostURL + location.pathname ),
docBase = docLocation;
if ($base.length){
var href = $base.attr("href");
if (href){
if (href.search(/^[^:\/]+:\/\/[^\/]+\/?/) === -1){
//the href is not absolute, we need to turn it into one
//so that we can turn paths stored in our location hash into
//relative paths.
if (href.charAt(0) === '/'){
//site relative url
docBase = hostURL + href;
}
else {
//the href is a document relative url
docBase = docLocation + href;
//XXX: we need some code here to calculate the final path
// just in case the docBase contains up-level (../) references.
}
}
else {
//the href is an absolute url
docBase = href;
}
}
//make sure docBase ends with a slash
docBase = docBase + (docBase.charAt(docBase.length - 1) === '/' ? ' ' : '/');
}
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ($base.length ? $base : $("<base>", { href: docBase }).prependTo( $head )),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ){
base.element.attr('href', docBase + path.get( href ));
},
//set the generated BASE element's href attribute to a new page's base path
reset: function(){
base.element.attr('href', docBase );
}
} : undefined;
//set location pathname from intial directory request
path.setOrigin();
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
function reFocus( page ){
var pageTitle = page.find( ".ui-title:eq(0)" );
if( pageTitle.length ){
pageTitle.focus();
}
else{
page.find( focusable ).eq(0).focus();
}
}
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ){
if( !!$activeClickedLink && (!$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval )){
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
//animation complete callback
$.fn.animationComplete = function( callback ){
if($.support.cssTransitions){
return $(this).one('webkitAnimationEnd', callback);
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout(callback, 0);
}
};
/* exposed $.mobile methods */
//update location.hash, with or without triggering hashchange event
//TODO - deprecate this one at 1.0
$.mobile.updateHash = path.set;
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//url stack, useful when plugins need to be aware of previous pages viewed
//TODO: deprecate this one at 1.0
$.mobile.urlstack = urlHistory.stack;
//history stack
$.mobile.urlHistory = urlHistory;
// changepage function
// TODO : consider moving args to an object hash
$.mobile.changePage = function( to, transition, reverse, changeHash, fromHashChange ){
//from is always the currently viewed page
var toIsArray = $.type(to) === "array",
toIsObject = $.type(to) === "object",
from = toIsArray ? to[0] : $.mobile.activePage;
to = toIsArray ? to[1] : to;
var url = $.type(to) === "string" ? path.stripHash( to ) : "",
fileUrl = url,
data,
type = 'get',
isFormRequest = false,
duplicateCachedPage = null,
currPage = urlHistory.getActive(),
back = false,
forward = false;
// If we are trying to transition to the same page that we are currently on ignore the request.
// an illegal same page request is defined by the current page being the same as the url, as long as there's history
// and to is not an array or object (those are allowed to be "same")
if( currPage && urlHistory.stack.length > 1 && currPage.url === url && !toIsArray && !toIsObject ) {
return;
}
else if(isPageTransitioning) {
pageTransitionQueue.unshift(arguments);
return;
}
isPageTransitioning = true;
// if the changePage was sent from a hashChange event
// guess if it came from the history menu
if( fromHashChange ){
// check if url is in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i ){
//if the url is in the stack, it's a forward or a back
if( this.url === url ){
urlIndex = i;
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
//forward set to opposite of back
forward = !back;
//reset activeIndex to this one
urlHistory.activeIndex = i;
}
});
//if it's a back, use reverse animation
if( back ){
reverse = true;
transition = transition || currPage.transition;
}
else if ( forward ){
transition = transition || urlHistory.getActive().transition;
}
}
if( toIsObject && to.url ){
url = to.url;
data = to.data;
type = to.type;
isFormRequest = true;
//make get requests bookmarkable
if( data && type === 'get' ){
if($.type( data ) === "object" ){
data = $.param(data);
}
url += "?" + data;
data = undefined;
}
}
//reset base to pathname for new request
if(base){ base.reset(); }
//kill the keyboard
$( window.document.activeElement ).add( "input:focus, textarea:focus, select:focus" ).blur();
function defaultTransition(){
if(transition === undefined){
transition = ( nextPageRole && nextPageRole === 'dialog' ) ? 'pop' : $.mobile.defaultTransition;
}
}
function releasePageTransitionLock(){
isPageTransitioning = false;
if(pageTransitionQueue.length>0) {
$.mobile.changePage.apply($.mobile, pageTransitionQueue.pop());
}
}
//function for transitioning between two existing pages
function transitionPages() {
$.mobile.silentScroll();
//get current scroll distance
var currScroll = $window.scrollTop(),
perspectiveTransitions = [ "flip" ],
pageContainerClasses = [];
//support deep-links to generated sub-pages
if( url.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ){
to = $( "[data-url='" + url + "']" );
}
if( from ){
//set as data for returning to that spot
from.data( "lastScroll", currScroll);
//trigger before show/hide events
from.data( "page" )._trigger( "beforehide", { nextPage: to } );
}
to.data( "page" )._trigger( "beforeshow", { prevPage: from || $("") } );
function loadComplete(){
if( changeHash !== false && url ){
//disable hash listening temporarily
urlHistory.ignoreNextHashChange = false;
//update hash and history
path.set( url );
}
//add page to history stack if it's not back or forward
if( !back && !forward ){
urlHistory.addNew( url, transition );
}
removeActiveLinkClass();
//jump to top or prev scroll, sometimes on iOS the page has not rendered yet. I could only get by this with a setTimeout, but would like to avoid that.
$.mobile.silentScroll( to.data( "lastScroll" ) );
reFocus( to );
//trigger show/hide events
if( from ){
from.data( "page" )._trigger( "hide", null, { nextPage: to } );
}
//trigger pageshow, define prevPage as either from or empty jQuery obj
to.data( "page" )._trigger( "show", null, { prevPage: from || $("") } );
//set "to" as activePage
$.mobile.activePage = to;
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if (duplicateCachedPage !== null) {
duplicateCachedPage.remove();
}
//remove initial build class (only present on first pageshow)
$html.removeClass( "ui-mobile-rendering" );
releasePageTransitionLock();
}
function addContainerClass(className){
$.mobile.pageContainer.addClass(className);
pageContainerClasses.push(className);
}
function removeContainerClasses(){
$.mobile
.pageContainer
.removeClass(pageContainerClasses.join(" "));
pageContainerClasses = [];
}
if(transition && (transition !== 'none')){
$.mobile.pageLoading( true );
if( $.inArray(transition, perspectiveTransitions) >= 0 ){
addContainerClass('ui-mobile-viewport-perspective');
}
addContainerClass('ui-mobile-viewport-transitioning');
if( from ){
from.addClass( transition + " out " + ( reverse ? "reverse" : "" ) );
}
to.addClass( $.mobile.activePageClass + " " + transition +
" in " + ( reverse ? "reverse" : "" ) );
// callback - remove classes, etc
to.animationComplete(function() {
to.add(from).removeClass("out in reverse " + transition );
if( from ){
from.removeClass( $.mobile.activePageClass );
}
loadComplete();
removeContainerClasses();
});
}
else{
$.mobile.pageLoading( true );
if( from ){
from.removeClass( $.mobile.activePageClass );
}
to.addClass( $.mobile.activePageClass );
loadComplete();
}
}
//shared page enhancements
function enhancePage(){
//set next page role, if defined
if ( nextPageRole || to.data('role') === 'dialog' ) {
url = urlHistory.getActive().url + dialogHashKey;
if(nextPageRole){
to.attr( "data-role", nextPageRole );
nextPageRole = null;
}
}
//run page plugin
to.page();
}
//if url is a string
if( url ){
to = $( "[data-url='" + url + "']" );
fileUrl = path.getFilePath(url);
}
else{ //find base url of element, if avail
var toID = to.attr('data-url'),
toIDfileurl = path.getFilePath(toID);
if(toID !== toIDfileurl){
fileUrl = toIDfileurl;
}
}
// ensure a transition has been set where pop is undefined
defaultTransition();
// find the "to" page, either locally existing in the dom or by creating it through ajax
if ( to.length && !isFormRequest ) {
if( fileUrl && base ){
base.set( fileUrl );
}
enhancePage();
transitionPages();
} else {
//if to exists in DOM, save a reference to it in duplicateCachedPage for removal after page change
if( to.length ){
duplicateCachedPage = to;
}
$.mobile.pageLoading();
$.ajax({
url: fileUrl,
type: type,
data: data,
dataType: "html",
success: function( html ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $("<div></div>"),
redirectLoc,
// TODO handle dialogs again
pageElemRegex = /.*(<[^>]*\bdata-role=["']?page["']?[^>]*>).*/,
dataUrlRegex = /\bdata-url=["']?([^"'>]*)["']?/;
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if(pageElemRegex.test(html) && RegExp.$1 && dataUrlRegex.test(RegExp.$1) && RegExp.$1) {
redirectLoc = RegExp.$1;
}
if( redirectLoc ){
if(base){
base.set( redirectLoc );
}
url = fileUrl = path.getFilePath( redirectLoc );
}
else {
if(base){
base.set(fileUrl);
}
}
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
to
.attr( "data-url", fileUrl )
.appendTo( $.mobile.pageContainer );
enhancePage();
setTimeout(function() { transitionPages(); }, 0);
},
error: function() {
$.mobile.pageLoading( true );
removeActiveLinkClass(true);
if(base){
base.set(path.get());
}
$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>Error Loading Page</h1></div>")
.css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 800 )
.fadeOut( 400, function(){
$(this).remove();
});
releasePageTransitionLock();
}
});
}
};
/* Event Bindings - hashchange, submit, and click */
//bind to form submit events, handle with Ajax
$( "form[data-ajax!='false']" ).live('submit', function(event){
if( !$.mobile.ajaxEnabled ||
//TODO: deprecated - remove at 1.0
!$.mobile.ajaxFormsEnabled ){ return; }
var type = $(this).attr("method"),
url = path.clean( $(this).attr( "action" ) );
//external submits use regular HTTP
if( path.isExternal( url ) ){
return;
}
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
$.mobile.changePage({
url: url,
type: type,
data: $(this).serialize()
},
undefined,
undefined,
true
);
event.preventDefault();
});
//click routing - direct to HTTP or Ajax, accordingly
$( "a" ).live( "click", function(event) {
var $this = $(this),
//get href, if defined, otherwise fall to null #
href = $this.attr( "href" ) || "#",
//get href, remove same-domain protocol and host
url = path.clean( href ),
//rel set to external
isRelExternal = $this.is( "[rel='external']" ),
//rel set to external
isEmbeddedPage = path.isEmbeddedPage( url ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = path.isExternal( url ) || (isRelExternal && !isEmbeddedPage),
//if target attr is specified we mimic _blank... for now
hasTarget = $this.is( "[target]" ),
//if data-ajax attr is set to false, use the default behavior of a link
hasAjaxDisabled = $this.is( "[data-ajax='false']" );
//if there's a data-rel=back attr, go back in history
if( $this.is( "[data-rel='back']" ) ){
window.history.back();
return false;
}
if( url === "#" ){
//for links created purely for interaction - ignore
event.preventDefault();
return;
}
$activeClickedLink = $this.closest( ".ui-btn" ).addClass( $.mobile.activeBtnClass );
if( isExternal || hasAjaxDisabled || hasTarget || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
!$.mobile.ajaxLinksEnabled ){
//remove active link class if external (then it won't be there if you come back)
removeActiveLinkClass(true);
//deliberately redirect, in case click was triggered
if( hasTarget ){
window.open( url );
}
else if( hasAjaxDisabled ){
return;
}
else{
location.href = url;
}
}
else {
//use ajax
var transition = $this.data( "transition" ),
direction = $this.data("direction"),
reverse = (direction && direction === "reverse") ||
// deprecated - remove by 1.0
$this.data( "back" );
//this may need to be more specific as we use data-rel more
nextPageRole = $this.attr( "data-rel" );
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
url = path.stripHash( url );
$.mobile.changePage( url, transition, reverse);
}
event.preventDefault();
});
//hashchange event handler
$window.bind( "hashchange", function( e, triggered ) {
//find first page via hash
var to = path.stripHash( location.hash ),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? false : undefined;
//if listening is disabled (either globally or temporarily), or it's a dialog hash
if( !$.mobile.hashListeningEnabled || !urlHistory.ignoreNextHashChange ||
(urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 && !$.mobile.activePage.is( ".ui-dialog" ))
){
if( !urlHistory.ignoreNextHashChange ){
urlHistory.ignoreNextHashChange = true;
}
return;
}
//if to is defined, load it
if ( to ){
$.mobile.changePage( to, transition, undefined, false, true );
}
//there's no hash, go to the first page in the dom
else {
$.mobile.changePage( $.mobile.firstPage, transition, true, false, true );
}
});
})( jQuery );
| js/jquery.mobile.navigation.js | /*
* jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt,
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {
//define vars for interal use
var $window = $(window),
$html = $('html'),
$head = $('head'),
//url path helpers for use in relative url management
path = {
//get path from current hash, or from a file path
get: function( newPath ){
if( newPath === undefined ){
newPath = location.hash;
}
return path.stripHash( newPath ).replace(/[^\/]*\.[^\/*]+$/, '');
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ){
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ){
location.hash = path;
},
//location pathname from intial directory request
origin: '',
setOrigin: function(){
path.origin = path.get( location.protocol + '//' + location.host + location.pathname );
},
//prefix a relative url with the current path
makeAbsolute: function( url ){
return path.get() + url;
},
//return a url path with the window's location protocol/hostname removed
clean: function( url ){
return url.replace( location.protocol + "//" + location.host, "");
},
//just return the url without an initial #
stripHash: function( url ){
return url.replace( /^#/, "" );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ){
return path.hasProtocol( path.clean( url ) );
},
hasProtocol: function( url ){
return (/^(:?\w+:)/).test( url );
},
//check if the url is relative
isRelative: function( url ){
return (/^[^\/|#]/).test( url ) && !path.hasProtocol( url );
},
isEmbeddedPage: function( url ){
return (/^#/).test( url );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
//array of pages that are visited during a single page load. each has a url and optional transition
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function(){
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function(){
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function(){
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition ){
//if there's forward history, wipe it
if( urlHistory.getNext() ){
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function(){
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
//disable hashchange event listener internally to ignore one change
//toggled internally when location.hash is updated to match the url of a successful page load
ignoreNextHashChange: true
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//contains role for next page, if defined on clicked link via data-rel
nextPageRole = null,
//queue to hold simultanious page transitions
pageTransitionQueue = [],
// indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children("base"),
hostURL = location.protocol + '//' + location.host,
docLocation = path.get( hostURL + location.pathname ),
docBase = docLocation;
if ($base.length){
var href = $base.attr("href");
if (href){
if (href.search(/^[^:\/]+:\/\/[^\/]+\/?/) === -1){
//the href is not absolute, we need to turn it into one
//so that we can turn paths stored in our location hash into
//relative paths.
if (href.charAt(0) === '/'){
//site relative url
docBase = hostURL + href;
}
else {
//the href is a document relative url
docBase = docLocation + href;
//XXX: we need some code here to calculate the final path
// just in case the docBase contains up-level (../) references.
}
}
else {
//the href is an absolute url
docBase = href;
}
}
//make sure docBase ends with a slash
docBase = docBase + (docBase.charAt(docBase.length - 1) === '/' ? ' ' : '/');
}
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ($base.length ? $base : $("<base>", { href: docBase }).prependTo( $head )),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ){
base.element.attr('href', docBase + path.get( href ));
},
//set the generated BASE element's href attribute to a new page's base path
reset: function(){
base.element.attr('href', docBase );
}
} : undefined;
//set location pathname from intial directory request
path.setOrigin();
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
function reFocus( page ){
var pageTitle = page.find( ".ui-title:eq(0)" );
if( pageTitle.length ){
pageTitle.focus();
}
else{
page.find( focusable ).eq(0).focus();
}
}
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ){
if( !!$activeClickedLink && (!$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval )){
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
//animation complete callback
$.fn.animationComplete = function( callback ){
if($.support.cssTransitions){
return $(this).one('webkitAnimationEnd', callback);
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout(callback, 0);
}
};
/* exposed $.mobile methods */
//update location.hash, with or without triggering hashchange event
//TODO - deprecate this one at 1.0
$.mobile.updateHash = path.set;
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//url stack, useful when plugins need to be aware of previous pages viewed
//TODO: deprecate this one at 1.0
$.mobile.urlstack = urlHistory.stack;
//history stack
$.mobile.urlHistory = urlHistory;
// changepage function
// TODO : consider moving args to an object hash
$.mobile.changePage = function( to, transition, reverse, changeHash, fromHashChange ){
//from is always the currently viewed page
var toIsArray = $.type(to) === "array",
toIsObject = $.type(to) === "object",
from = toIsArray ? to[0] : $.mobile.activePage;
to = toIsArray ? to[1] : to;
var url = $.type(to) === "string" ? path.stripHash( to ) : "",
fileUrl = url,
data,
type = 'get',
isFormRequest = false,
duplicateCachedPage = null,
currPage = urlHistory.getActive(),
back = false,
forward = false;
// If we are trying to transition to the same page that we are currently on ignore the request.
// an illegal same page request is defined by the current page being the same as the url, as long as there's history
// and to is not an array or object (those are allowed to be "same")
if( currPage && urlHistory.stack.length > 1 && currPage.url === url && !toIsArray && !toIsObject ) {
return;
}
else if(isPageTransitioning) {
pageTransitionQueue.unshift(arguments);
return;
}
isPageTransitioning = true;
// if the changePage was sent from a hashChange event
// guess if it came from the history menu
if( fromHashChange ){
// check if url is in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i ){
//if the url is in the stack, it's a forward or a back
if( this.url === url ){
urlIndex = i;
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
//forward set to opposite of back
forward = !back;
//reset activeIndex to this one
urlHistory.activeIndex = i;
}
});
//if it's a back, use reverse animation
if( back ){
reverse = true;
transition = transition || currPage.transition;
}
else if ( forward ){
transition = transition || urlHistory.getActive().transition;
}
}
if( toIsObject && to.url ){
url = to.url;
data = to.data;
type = to.type;
isFormRequest = true;
//make get requests bookmarkable
if( data && type === 'get' ){
if($.type( data ) === "object" ){
data = $.param(data);
}
url += "?" + data;
data = undefined;
}
}
//reset base to pathname for new request
if(base){ base.reset(); }
//kill the keyboard
$( window.document.activeElement ).add( "input:focus, textarea:focus, select:focus" ).blur();
function defaultTransition(){
if(transition === undefined){
transition = ( nextPageRole && nextPageRole === 'dialog' ) ? 'pop' : $.mobile.defaultTransition;
}
}
function releasePageTransitionLock(){
isPageTransitioning = false;
if(pageTransitionQueue.length>0) {
$.mobile.changePage.apply($.mobile, pageTransitionQueue.pop());
}
}
//function for transitioning between two existing pages
function transitionPages() {
$.mobile.silentScroll();
//get current scroll distance
var currScroll = $window.scrollTop(),
perspectiveTransitions = [ "flip" ],
pageContainerClasses = [];
//support deep-links to generated sub-pages
if( url.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ){
to = $( "[data-url='" + url + "']" );
}
if( from ){
//set as data for returning to that spot
from.data( "lastScroll", currScroll);
//trigger before show/hide events
from.data( "page" )._trigger( "beforehide", { nextPage: to } );
}
to.data( "page" )._trigger( "beforeshow", { prevPage: from || $("") } );
function loadComplete(){
if( changeHash !== false && url ){
//disable hash listening temporarily
urlHistory.ignoreNextHashChange = false;
//update hash and history
path.set( url );
}
//add page to history stack if it's not back or forward
if( !back && !forward ){
urlHistory.addNew( url, transition );
}
removeActiveLinkClass();
//jump to top or prev scroll, sometimes on iOS the page has not rendered yet. I could only get by this with a setTimeout, but would like to avoid that.
$.mobile.silentScroll( to.data( "lastScroll" ) );
reFocus( to );
//trigger show/hide events
if( from ){
from.data( "page" )._trigger( "hide", null, { nextPage: to } );
}
//trigger pageshow, define prevPage as either from or empty jQuery obj
to.data( "page" )._trigger( "show", null, { prevPage: from || $("") } );
//set "to" as activePage
$.mobile.activePage = to;
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if (duplicateCachedPage !== null) {
duplicateCachedPage.remove();
}
//remove initial build class (only present on first pageshow)
$html.removeClass( "ui-mobile-rendering" );
releasePageTransitionLock();
}
function addContainerClass(className){
$.mobile.pageContainer.addClass(className);
pageContainerClasses.push(className);
}
function removeContainerClasses(){
$.mobile
.pageContainer
.removeClass(pageContainerClasses.join(" "));
pageContainerClasses = [];
}
if(transition && (transition !== 'none')){
$.mobile.pageLoading( true );
if( $.inArray(transition, perspectiveTransitions) >= 0 ){
addContainerClass('ui-mobile-viewport-perspective');
}
addContainerClass('ui-mobile-viewport-transitioning');
if( from ){
from.addClass( transition + " out " + ( reverse ? "reverse" : "" ) );
}
to.addClass( $.mobile.activePageClass + " " + transition +
" in " + ( reverse ? "reverse" : "" ) );
// callback - remove classes, etc
to.animationComplete(function() {
to.add(from).removeClass("out in reverse " + transition );
if( from ){
from.removeClass( $.mobile.activePageClass );
}
loadComplete();
removeContainerClasses();
});
}
else{
$.mobile.pageLoading( true );
if( from ){
from.removeClass( $.mobile.activePageClass );
}
to.addClass( $.mobile.activePageClass );
loadComplete();
}
}
//shared page enhancements
function enhancePage(){
//set next page role, if defined
if ( nextPageRole || to.data('role') === 'dialog' ) {
url = urlHistory.getActive().url + dialogHashKey;
if(nextPageRole){
to.attr( "data-role", nextPageRole );
nextPageRole = null;
}
}
//run page plugin
to.page();
}
//if url is a string
if( url ){
to = $( "[data-url='" + url + "']" );
fileUrl = path.getFilePath(url);
}
else{ //find base url of element, if avail
var toID = to.attr('data-url'),
toIDfileurl = path.getFilePath(toID);
if(toID !== toIDfileurl){
fileUrl = toIDfileurl;
}
}
// ensure a transition has been set where pop is undefined
defaultTransition();
// find the "to" page, either locally existing in the dom or by creating it through ajax
if ( to.length && !isFormRequest ) {
if( fileUrl && base ){
base.set( fileUrl );
}
enhancePage();
transitionPages();
} else {
//if to exists in DOM, save a reference to it in duplicateCachedPage for removal after page change
if( to.length ){
duplicateCachedPage = to;
}
$.mobile.pageLoading();
$.ajax({
url: fileUrl,
type: type,
data: data,
success: function( html ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $("<div></div>"),
redirectLoc,
// TODO handle dialogs again
pageElemRegex = /.*(<[^>]*\bdata-role=["']?page["']?[^>]*>).*/,
dataUrlRegex = /\bdata-url=["']?([^"'>]*)["']?/;
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if(pageElemRegex.test(html) && RegExp.$1 && dataUrlRegex.test(RegExp.$1) && RegExp.$1) {
redirectLoc = RegExp.$1;
}
if( redirectLoc ){
if(base){
base.set( redirectLoc );
}
url = fileUrl = path.getFilePath( redirectLoc );
}
else {
if(base){
base.set(fileUrl);
}
}
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
to
.attr( "data-url", fileUrl )
.appendTo( $.mobile.pageContainer );
enhancePage();
setTimeout(function() { transitionPages(); }, 0);
},
error: function() {
$.mobile.pageLoading( true );
removeActiveLinkClass(true);
if(base){
base.set(path.get());
}
$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>Error Loading Page</h1></div>")
.css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 800 )
.fadeOut( 400, function(){
$(this).remove();
});
releasePageTransitionLock();
}
});
}
};
/* Event Bindings - hashchange, submit, and click */
//bind to form submit events, handle with Ajax
$( "form[data-ajax!='false']" ).live('submit', function(event){
if( !$.mobile.ajaxEnabled ||
//TODO: deprecated - remove at 1.0
!$.mobile.ajaxFormsEnabled ){ return; }
var type = $(this).attr("method"),
url = path.clean( $(this).attr( "action" ) );
//external submits use regular HTTP
if( path.isExternal( url ) ){
return;
}
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
$.mobile.changePage({
url: url,
type: type,
data: $(this).serialize()
},
undefined,
undefined,
true
);
event.preventDefault();
});
//click routing - direct to HTTP or Ajax, accordingly
$( "a" ).live( "click", function(event) {
var $this = $(this),
//get href, if defined, otherwise fall to null #
href = $this.attr( "href" ) || "#",
//get href, remove same-domain protocol and host
url = path.clean( href ),
//rel set to external
isRelExternal = $this.is( "[rel='external']" ),
//rel set to external
isEmbeddedPage = path.isEmbeddedPage( url ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = path.isExternal( url ) || (isRelExternal && !isEmbeddedPage),
//if target attr is specified we mimic _blank... for now
hasTarget = $this.is( "[target]" ),
//if data-ajax attr is set to false, use the default behavior of a link
hasAjaxDisabled = $this.is( "[data-ajax='false']" );
//if there's a data-rel=back attr, go back in history
if( $this.is( "[data-rel='back']" ) ){
window.history.back();
return false;
}
if( url === "#" ){
//for links created purely for interaction - ignore
event.preventDefault();
return;
}
$activeClickedLink = $this.closest( ".ui-btn" ).addClass( $.mobile.activeBtnClass );
if( isExternal || hasAjaxDisabled || hasTarget || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
!$.mobile.ajaxLinksEnabled ){
//remove active link class if external (then it won't be there if you come back)
removeActiveLinkClass(true);
//deliberately redirect, in case click was triggered
if( hasTarget ){
window.open( url );
}
else if( hasAjaxDisabled ){
return;
}
else{
location.href = url;
}
}
else {
//use ajax
var transition = $this.data( "transition" ),
direction = $this.data("direction"),
reverse = (direction && direction === "reverse") ||
// deprecated - remove by 1.0
$this.data( "back" );
//this may need to be more specific as we use data-rel more
nextPageRole = $this.attr( "data-rel" );
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
url = path.stripHash( url );
$.mobile.changePage( url, transition, reverse);
}
event.preventDefault();
});
//hashchange event handler
$window.bind( "hashchange", function( e, triggered ) {
//find first page via hash
var to = path.stripHash( location.hash ),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? false : undefined;
//if listening is disabled (either globally or temporarily), or it's a dialog hash
if( !$.mobile.hashListeningEnabled || !urlHistory.ignoreNextHashChange ||
(urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 && !$.mobile.activePage.is( ".ui-dialog" ))
){
if( !urlHistory.ignoreNextHashChange ){
urlHistory.ignoreNextHashChange = true;
}
return;
}
//if to is defined, load it
if ( to ){
$.mobile.changePage( to, transition, undefined, false, true );
}
//there's no hash, go to the first page in the dom
else {
$.mobile.changePage( $.mobile.firstPage, transition, true, false, true );
}
});
})( jQuery );
| Fix for the remainder of issue 991.
- Looks like the "Intelligent Guess" default behavior of the $.ajax() method in jQuery 1.5.1 guesses wrong when attempting to load an HTML file via a file:// URL. It's guessing that it is an XML document, so it ends up passing in the DOM document node to our success callback, instead of the expected HTML as text (responseText), so our callback code does not behave correctly. We can get around this by simply specifying dataType:"html" at the time we make a request.
| js/jquery.mobile.navigation.js | Fix for the remainder of issue 991. | <ide><path>s/jquery.mobile.navigation.js
<ide> url: fileUrl,
<ide> type: type,
<ide> data: data,
<add> dataType: "html",
<ide> success: function( html ) {
<ide> //pre-parse html to check for a data-url,
<ide> //use it as the new fileUrl, base path, etc |
|
Java | mit | c70c3f4ed7526c5de8bda49012a8d152fa132f5f | 0 | razreg/ubongo,razreg/ubongo,razreg/ubongo,razreg/ubongo,razreg/ubongo | package ubongo.common.constants;
public class MachineConstants {
public static final String SERVER_FALLBACK = "nova.cs.tau.ac.il";
public static final String BASE_UNIT_REQUEST = "Unit task";
public static final String KILL_TASK_REQUEST = "Kill unit task";
public static final String UPDATE_TASK_REQUEST = "Update task status";
public static final String INPUT_DIR_SUFFIX = "_ubongo_in";
public static final String OUTPUT_DIR_SUFFIX = "_ubongo_out";
public static final String ARG_SERVER = "server";
public static final String ARG_DIR = "base_dir";
public static final String ARG_UNITS = "units_dir";
public static final String ARG_QUERIES_PATH = "queries";
public static final String ARG_CONFIG_PATH = "config";
}
| infra/common/src/main/java/ubongo/common/constants/MachineConstants.java | package ubongo.common.constants;
public class MachineConstants {
public static final String SERVER_FALLBACK = "nova.cs.tau.ac.il";
public static final String BASE_UNIT_REQUEST = "Unit task";
public static final String KILL_TASK_REQUEST = "Kill unit task";
public static final String UPDATE_TASK_REQUEST = "Update task status";
public static String GET_MACHINE_PERFORMANCE = "Get machine performance request";
public static final String INPUT_DIR_SUFFIX = "_ubongo_in";
public static final String OUTPUT_DIR_SUFFIX = "_ubongo_out";
public static final String ARG_SERVER = "server";
public static final String ARG_DIR = "base_dir";
public static final String ARG_UNITS = "units_dir";
public static final String ARG_QUERIES_PATH = "queries";
public static final String ARG_CONFIG_PATH = "config";
}
| Machine changes
| infra/common/src/main/java/ubongo/common/constants/MachineConstants.java | Machine changes | <ide><path>nfra/common/src/main/java/ubongo/common/constants/MachineConstants.java
<ide> public static final String BASE_UNIT_REQUEST = "Unit task";
<ide> public static final String KILL_TASK_REQUEST = "Kill unit task";
<ide> public static final String UPDATE_TASK_REQUEST = "Update task status";
<del> public static String GET_MACHINE_PERFORMANCE = "Get machine performance request";
<ide>
<ide> public static final String INPUT_DIR_SUFFIX = "_ubongo_in";
<ide> public static final String OUTPUT_DIR_SUFFIX = "_ubongo_out"; |
|
Java | apache-2.0 | 08a2e80f4b6245bb786feb65fd70aad3bd96c762 | 0 | apache/npanday,apache/npanday,apache/npanday,apache/npanday | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package npanday.dao.impl;
import npanday.ArtifactType;
import npanday.ArtifactTypeHelper;
import npanday.PathUtil;
import npanday.dao.Project;
import npanday.dao.ProjectDao;
import npanday.dao.ProjectDependency;
import npanday.dao.ProjectFactory;
import npanday.dao.ProjectUri;
import npanday.dao.Requirement;
import npanday.registry.RepositoryRegistry;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.DefaultConsumer;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.openrdf.OpenRDFException;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public final class ProjectDaoImpl
implements ProjectDao
{
private String className;
private String id;
private static Logger logger = Logger.getAnonymousLogger();
private org.openrdf.repository.Repository rdfRepository;
/**
* The artifact factory component, which is used for creating artifacts.
*/
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
private int getProjectForCounter = 0;
private int storeCounter = 0;
private RepositoryConnection repositoryConnection;
private String dependencyQuery;
private String projectQuery;
private ArtifactResolver artifactResolver;
public void init( ArtifactFactory artifactFactory, ArtifactResolver artifactResolver )
{
this.artifactFactory = artifactFactory;
this.artifactResolver = artifactResolver;
List<ProjectUri> projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
dependencyQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
projectUris.add( ProjectUri.PARENT );
projectQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
}
public Set<Project> getAllProjects()
throws IOException
{
Set<Project> projects = new HashSet<Project>();
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
result = tupleQuery.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
String groupId = set.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString();
String version = set.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString();
String artifactId = set.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString();
String artifactType =
set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString();
String classifier = null;
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
classifier = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() ).getValue().toString();
}
// Project project = getProjectFor( groupId, artifactId, version, artifactType, null );
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
projects.add( getProjectFor( groupId, artifactId, version, artifactType, classifier ) );
}
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-000: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-001: Message = " + e.getMessage() );
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-002: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
return projects;
}
public void setRdfRepository( Repository repository )
{
this.rdfRepository = repository;
}
public boolean openConnection()
{
try
{
repositoryConnection = rdfRepository.getConnection();
repositoryConnection.setAutoCommit( false );
}
catch ( RepositoryException e )
{
return false;
}
return true;
}
public boolean closeConnection()
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.commit();
repositoryConnection.close();
}
catch ( RepositoryException e )
{
return false;
}
}
return true;
}
public void removeProjectFor( String groupId, String artifactId, String version, String artifactType )
throws IOException
{
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id = valueFactory.createURI( groupId + ":" + artifactId + ":" + version + ":" + artifactType );
try
{
repositoryConnection.remove( repositoryConnection.getStatements( id, null, null, true ) );
}
catch ( RepositoryException e )
{
throw new IOException( e.getMessage() );
}
}
public Project getProjectFor( String groupId, String artifactId, String version, String artifactType,
String publicKeyTokenId )
throws IOException
{
long startTime = System.currentTimeMillis();
ValueFactory valueFactory = rdfRepository.getValueFactory();
ProjectDependency project = new ProjectDependency();
project.setArtifactId( artifactId );
project.setGroupId( groupId );
project.setVersion( version );
project.setArtifactType( artifactType );
project.setPublicKeyTokenId( publicKeyTokenId );
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
tupleQuery.setBinding( ProjectUri.GROUP_ID.getObjectBinding(), valueFactory.createLiteral( groupId ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_ID.getObjectBinding(), valueFactory.createLiteral( artifactId ) );
tupleQuery.setBinding( ProjectUri.VERSION.getObjectBinding(), valueFactory.createLiteral( version ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding(),
valueFactory.createLiteral( artifactType ) );
if ( publicKeyTokenId != null )
{
tupleQuery.setBinding( ProjectUri.CLASSIFIER.getObjectBinding(),
valueFactory.createLiteral( publicKeyTokenId ) );
project.setPublicKeyTokenId( publicKeyTokenId.replace( ":", "" ) );
}
result = tupleQuery.evaluate();
if ( !result.hasNext() )
{
//if ( artifactType != null && ArtifactTypeHelper.isDotnetAnyGac( artifactType ) )
if ( artifactType != null )
{
Artifact artifact = createArtifactFrom( project, artifactFactory );
if ( !artifact.getFile().exists() )
{
throw new IOException( "NPANDAY-180-123: Could not find GAC assembly: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = "
+ artifactType + ", File Path = " + artifact.getFile().getAbsolutePath() );
}
project.setResolved( true );
return project;
}
throw new IOException( "NPANDAY-180-124: Could not find the project: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = " + artifactType );
}
while ( result.hasNext() )
{
BindingSet set = result.next();
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
if ( set.hasBinding( ProjectUri.IS_RESOLVED.getObjectBinding() )
&& set.getBinding( ProjectUri.IS_RESOLVED.getObjectBinding() ).getValue().toString().equalsIgnoreCase(
"true" ) )
{
project.setResolved( true );
}
project.setArtifactType( set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
/*
* if ( set.hasBinding( ProjectUri.PARENT.getObjectBinding() ) ) { String pid = set.getBinding(
* ProjectUri.PARENT.getObjectBinding() ).getValue().toString(); String[] tokens = pid.split( "[:]" );
* Project parentProject = getProjectFor( tokens[0], tokens[1], tokens[2], null, null );
* project.setParentProject( parentProject ); }
*/
if ( set.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.DEPENDENCY.getObjectBinding() );
addDependenciesToProject( project, repositoryConnection, binding.getValue() );
}
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
addClassifiersToProject( project, repositoryConnection, binding.getValue() );
}
}
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-005: Message = " + e.getMessage() );
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-006: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-007: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
// TODO: If has parent, then need to modify dependencies, etc of returned project
logger.finest( "NPANDAY-180-008: ProjectDao.GetProjectFor - Artifact Id = " + project.getArtifactId()
+ ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = " + getProjectForCounter++ );
return project;
}
public Project getProjectFor( MavenProject mavenProject )
throws IOException
{
return getProjectFor( mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion(),
mavenProject.getArtifact().getType(), mavenProject.getArtifact().getClassifier() );
}
public void storeProject( Project project, File localRepository, List<ArtifactRepository> artifactRepositories )
throws IOException
{
}
/**
* Generates the system path for gac dependencies.
*/
private String generateDependencySystemPath( ProjectDependency projectDependency )
{
return new File( System.getenv( "SystemRoot" ), "/assembly/"
+ projectDependency.getArtifactType().toUpperCase() + "/" + projectDependency.getArtifactId() + "/"
+ projectDependency.getVersion() + "__" + projectDependency.getPublicKeyTokenId() + "/"
+ projectDependency.getArtifactId() + ".dll" ).getAbsolutePath();
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
return storeProjectAndResolveDependencies( project, localRepository, artifactRepositories,
new HashMap<String, Set<Artifact>>() );
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories,
Map<String, Set<Artifact>> cache )
throws IOException, IllegalArgumentException
{
String key = getKey( project );
if ( cache.containsKey( key ) )
{
return cache.get( key );
}
long startTime = System.currentTimeMillis();
String snapshotVersion;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories, cache ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
Artifact assembly = createArtifactFrom( projectDependency, artifactFactory );
snapshotVersion = null;
if(!assembly.getFile().exists())
{
try
{
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-181-121: Problem in resolving assembly: " + assembly.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-181-122: Problem in resolving assembly: " + assembly.toString()
+ ", Message = " + e.getMessage() );
}
}
logger.info( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File dependencyFile = PathUtil.getDotNetArtifact( assembly , localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
//we have already set file for the assembly above (in createArtifactFrom) so we do not need re-resovle it
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
if (assembly.getFile().exists())
{
projectDependency.setSystemPath( assembly.getFile().getAbsolutePath());
projectDependency.setResolved( true );
assembly.setResolved( true );
}
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
// re-resolve snapshots
if ( !assembly.isSnapshot() )
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
projectDependency = (ProjectDependency) dep;
artifactDependencies.add( assembly );
Set<Artifact> deps = this.storeProjectAndResolveDependencies( projectDependency,
localRepository,
artifactRepositories,
cache );
artifactDependencies.addAll( deps );
}
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
logger.finest("NPANDAY-180-055: dependency:" + projectDependency.getClass());
logger.finest("NPANDAY-180-056: dependency:" + assembly.getClass());
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
logger.finest( "NPANDAY-180-016: set file....");
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
if( model.getArtifactId().equals( projectDependency.getArtifactId() ) && projectDependency.isResolved() )
{
modelDependencies.add( model );
}
}
}
logger.finest( "NPANDAY-180-019: set file...");
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File dotnetFile = PathUtil.getDotNetArtifact( assembly , localRepository );
logger.info( "NPANDAY-180-018: Not found in local repository, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed Path Check = " + dotnetFile.getAbsolutePath());
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ) || !dotnetFile.exists() )// TODO: Generalize to any attached artifact
{
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
projectDependency.setResolved( true );
if ( assembly != null && assembly.getFile().exists() )
{
dotnetFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), dotnetFile );
assembly.setFile( dotnetFile );
}
}
catch ( ArtifactNotFoundException e )
{
logger.log(Level.SEVERE, "NPANDAY-180-0201: Error resolving artifact. Reason:", e);
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.log( Level.SEVERE, "NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage(), e );
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
Project projectModel = ProjectFactory.createProjectFrom( model, null );
artifactDependencies.addAll( storeProjectAndResolveDependencies( projectModel, localRepository,
artifactRepositories, cache ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
cache.put( key, artifactDependencies );
return artifactDependencies;
}
private String getKey( Project project )
{
return project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion();
}
public Set<Artifact> storeModelAndResolveDependencies( Model model, File pomFileDirectory,
File localArtifactRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException
{
return storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model, pomFileDirectory ),
localArtifactRepository, artifactRepositories );
}
public String getClassName()
{
return className;
}
public String getID()
{
return id;
}
public void init( Object dataStoreObject, String id, String className )
throws IllegalArgumentException
{
if ( dataStoreObject == null || !( dataStoreObject instanceof org.openrdf.repository.Repository ) )
{
throw new IllegalArgumentException(
"NPANDAY-180-023: Must initialize with an instance of org.openrdf.repository.Repository" );
}
this.id = id;
this.className = className;
this.rdfRepository = (org.openrdf.repository.Repository) dataStoreObject;
}
public void setRepositoryRegistry( RepositoryRegistry repositoryRegistry )
{
}
protected void initForUnitTest( Object dataStoreObject, String id, String className,
ArtifactResolver artifactResolver, ArtifactFactory artifactFactory )
{
this.init( dataStoreObject, id, className );
init( artifactFactory, artifactResolver );
}
private void addClassifiersToProject( Project project, RepositoryConnection repositoryConnection,
Value classifierUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
String query = "SELECT * FROM {x} p {y}";
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, query );
tq.setBinding( "x", classifierUri );
TupleQueryResult result = tq.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
for ( Iterator<Binding> i = set.iterator(); i.hasNext(); )
{
Binding binding = i.next();
if ( binding.getValue().toString().startsWith( "http://maven.apache.org/artifact/requirement" ) )
{
try
{
project.addRequirement( Requirement.Factory.createDefaultRequirement(
new java.net.URI(
binding.getValue().toString() ),
set.getValue( "y" ).toString() ) );
}
catch ( URISyntaxException e )
{
e.printStackTrace();
}
}
}
}
}
private void addDependenciesToProject( Project project, RepositoryConnection repositoryConnection,
Value dependencyUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, dependencyQuery );
tq.setBinding( "x", dependencyUri );
TupleQueryResult dependencyResult = tq.evaluate();
try
{
while ( dependencyResult.hasNext() )
{
ProjectDependency projectDependency = new ProjectDependency();
BindingSet bs = dependencyResult.next();
projectDependency.setGroupId( bs.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactId( bs.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setVersion( bs.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactType( bs.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
Binding classifierBinding = bs.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
if ( classifierBinding != null )
{
projectDependency.setPublicKeyTokenId( classifierBinding.getValue().toString().replace( ":", "" ) );
}
project.addProjectDependency( projectDependency );
if ( bs.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
addDependenciesToProject( projectDependency, repositoryConnection,
bs.getValue( ProjectUri.DEPENDENCY.getObjectBinding() ) );
}
}
}
finally
{
dependencyResult.close();
}
}
private String constructQueryFragmentFor( String subject, List<ProjectUri> projectUris )
{
// ProjectUri nonOptionalUri = this.getNonOptionalUriFrom( projectUris );
// projectUris.remove( nonOptionalUri );
StringBuffer buffer = new StringBuffer();
buffer.append( subject );
for ( Iterator<ProjectUri> i = projectUris.iterator(); i.hasNext(); )
{
ProjectUri projectUri = i.next();
buffer.append( " " );
if ( projectUri.isOptional() )
{
buffer.append( "[" );
}
buffer.append( "<" ).append( projectUri.getPredicate() ).append( "> {" ).append(
projectUri.getObjectBinding() ).append(
"}" );
if ( projectUri.isOptional() )
{
buffer.append( "]" );
}
if ( i.hasNext() )
{
buffer.append( ";" );
}
}
return buffer.toString();
}
private ProjectUri getNonOptionalUriFrom( List<ProjectUri> projectUris )
{
for ( ProjectUri projectUri : projectUris )
{
if ( !projectUri.isOptional() )
{
return projectUri;
}
}
return null;
}
// TODO: move generateInteropDll, getInteropParameters, getTempDirectory, and execute methods to another class
private String generateInteropDll( String name, String classifier )
throws IOException
{
File tmpDir;
String comReferenceAbsolutePath = "";
try
{
tmpDir = getTempDirectory();
}
catch ( IOException e )
{
throw new IOException( "Unable to create temporary directory" );
}
try
{
comReferenceAbsolutePath = resolveComReferencePath( name, classifier );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
String interopAbsolutePath = tmpDir.getAbsolutePath() + File.separator + "Interop." + name + ".dll";
List<String> params = getInteropParameters( interopAbsolutePath, comReferenceAbsolutePath, name );
try
{
execute( "tlbimp", params );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
return interopAbsolutePath;
}
private String resolveComReferencePath( String name, String classifier )
throws Exception
{
String[] classTokens = classifier.split( "}" );
classTokens[1] = classTokens[1].replace( "-", "\\" );
String newClassifier = classTokens[0] + "}" + classTokens[1];
String registryPath = "HKEY_CLASSES_ROOT\\TypeLib\\" + newClassifier + "\\win32\\";
int lineNoOfPath = 1;
List<String> parameters = new ArrayList<String>();
parameters.add( "query" );
parameters.add( registryPath );
parameters.add( "/ve" );
StreamConsumer outConsumer = new StreamConsumerImpl();
StreamConsumer errorConsumer = new StreamConsumerImpl();
try
{
// TODO: investigate why outConsumer ignores newline
execute( "reg", parameters, outConsumer, errorConsumer );
}
catch ( Exception e )
{
throw new Exception( "Cannot find information of [" + name
+ "] ActiveX component in your system, you need to install this component first to continue." );
}
// parse outConsumer
String out = outConsumer.toString();
String tokens[] = out.split( "\n" );
String lineResult = "";
String[] result;
if ( tokens.length >= lineNoOfPath - 1 )
{
lineResult = tokens[lineNoOfPath - 1];
}
result = lineResult.split( "REG_SZ" );
if ( result.length > 1 )
{
return result[1].trim();
}
return null;
}
private List<String> readPomAttribute( String pomFileLoc, String tag )
{
List<String> attributes = new ArrayList<String>();
try
{
File file = new File( pomFileLoc );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( file );
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName( tag );
for ( int s = 0; s < nodeLst.getLength(); s++ )
{
Node currentNode = nodeLst.item( s );
NodeList childrenList = currentNode.getChildNodes();
for ( int i = 0; i < childrenList.getLength(); i++ )
{
Node child = childrenList.item( i );
attributes.add( child.getNodeValue() );
}
}
}
catch ( Exception e )
{
}
return attributes;
}
private List<String> getInteropParameters( String interopAbsolutePath, String comRerefenceAbsolutePath,
String namespace )
{
List<String> parameters = new ArrayList<String>();
parameters.add( comRerefenceAbsolutePath );
parameters.add( "/out:" + interopAbsolutePath );
parameters.add( "/namespace:" + namespace );
try
{
// beginning code for checking of strong name key or signing of projects
String key = "";
String keyfile = "";
String currentWorkingDir = System.getProperty( "user.dir" );
// Check if Parent pom
List<String> modules = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "module" );
if ( !modules.isEmpty() )
{
// check if there is a matching dependency with the namespace
for ( String child : modules )
{
// check each module pom file if there is existing keyfile
String tempDir = currentWorkingDir + File.separator + child;
try
{
List<String> keyfiles = readPomAttribute( tempDir + "\\pom.xml", "keyfile" );
if ( keyfiles.get( 0 ) != null )
{
// PROBLEM WITH MULTIMODULES
boolean hasComRef = false;
List<String> dependencies = readPomAttribute( tempDir + "\\pom.xml", "groupId" );
for ( String item : dependencies )
{
if ( item.equals( namespace ) )
{
hasComRef = true;
break;
}
}
if ( hasComRef )
{
key = keyfiles.get( 0 );
currentWorkingDir = tempDir;
}
}
}
catch ( Exception e )
{
}
}
}
else
{
// not a parent pom, so read project pom file for keyfile value
List<String> keyfiles = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "keyfile" );
key = keyfiles.get( 0 );
}
if ( key != "" )
{
keyfile = currentWorkingDir + File.separator + key;
parameters.add( "/keyfile:" + keyfile );
}
// end code for checking of strong name key or signing of projects
}
catch ( Exception ex )
{
}
return parameters;
}
private File getTempDirectory()
throws IOException
{
File tempFile = File.createTempFile( "interop-dll-", "" );
File tmpDir = new File( tempFile.getParentFile(), tempFile.getName() );
tempFile.delete();
tmpDir.mkdir();
return tmpDir;
}
// can't use dotnet-executable due to cyclic dependency.
private void execute( String executable, List<String> commands )
throws Exception
{
execute( executable, commands, null, null );
}
private void execute( String executable, List<String> commands, StreamConsumer systemOut, StreamConsumer systemError )
throws Exception
{
int result = 0;
Commandline commandline = new Commandline();
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()] ) );
try
{
result = CommandLineUtils.executeCommandLine( commandline, systemOut, systemError );
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline + ", Result = "
+ result );
if ( result != 0 )
{
throw new Exception( "NPANDAY-040-001: Could not execute: Command = " + commandline.toString()
+ ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new Exception( "NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
/**
* Creates an artifact using information from the specified project dependency.
*
* @param projectDependency a project dependency to use as the source of the returned artifact
* @param artifactFactory artifact factory used to create the artifact
* @return an artifact using information from the specified project dependency
*/
private static Artifact createArtifactFrom( ProjectDependency projectDependency, ArtifactFactory artifactFactory )
{
String groupId = projectDependency.getGroupId();
String artifactId = projectDependency.getArtifactId();
String version = projectDependency.getVersion();
String artifactType = projectDependency.getArtifactType();
String scope = ( projectDependency.getScope() == null ) ? Artifact.SCOPE_COMPILE : projectDependency.getScope();
String publicKeyTokenId = projectDependency.getPublicKeyTokenId();
if ( groupId == null )
{
logger.warning( "NPANDAY-180-001: Project Group ID is missing" );
}
if ( artifactId == null )
{
logger.warning( "NPANDAY-180-002: Project Artifact ID is missing: Group Id = " + groupId );
}
if ( version == null )
{
logger.warning( "NPANDAY-180-003: Project Version is missing: Group Id = " + groupId +
", Artifact Id = " + artifactId );
}
if ( artifactType == null )
{
logger.warning( "NPANDAY-180-004: Project Artifact Type is missing: Group Id" + groupId +
", Artifact Id = " + artifactId + ", Version = " + version );
}
Artifact assembly = artifactFactory.createDependencyArtifact( groupId, artifactId,
VersionRange.createFromVersion( version ),
artifactType, publicKeyTokenId, scope,
null );
//using PathUtil
File artifactFile = null;
if (ArtifactTypeHelper.isDotnetAnyGac( artifactType ))
{
if (!ArtifactTypeHelper.isDotnet4Gac(artifactType))
{
artifactFile = PathUtil.getGlobalAssemblyCacheFileFor( assembly, new File("C:\\WINDOWS\\assembly\\") );
}
else
{
artifactFile = PathUtil.getGACFile4Artifact(assembly);
}
}
else
{
artifactFile = PathUtil.getUserAssemblyCacheFileFor( assembly, new File( System.getProperty( "user.home" ),
File.separator + ".m2" + File.separator + "repository") );
}
assembly.setFile( artifactFile );
return assembly;
}
/**
* TODO: refactor this to another class and all methods concerning com_reference StreamConsumer instance that
* buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
}
| components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package npanday.dao.impl;
import npanday.ArtifactType;
import npanday.ArtifactTypeHelper;
import npanday.PathUtil;
import npanday.dao.Project;
import npanday.dao.ProjectDao;
import npanday.dao.ProjectDependency;
import npanday.dao.ProjectFactory;
import npanday.dao.ProjectUri;
import npanday.dao.Requirement;
import npanday.registry.RepositoryRegistry;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.DefaultConsumer;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.openrdf.OpenRDFException;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public final class ProjectDaoImpl
implements ProjectDao
{
private String className;
private String id;
private static Logger logger = Logger.getAnonymousLogger();
private org.openrdf.repository.Repository rdfRepository;
/**
* The artifact factory component, which is used for creating artifacts.
*/
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
private int getProjectForCounter = 0;
private int storeCounter = 0;
private RepositoryConnection repositoryConnection;
private String dependencyQuery;
private String projectQuery;
private ArtifactResolver artifactResolver;
public void init( ArtifactFactory artifactFactory, ArtifactResolver artifactResolver )
{
this.artifactFactory = artifactFactory;
this.artifactResolver = artifactResolver;
List<ProjectUri> projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
dependencyQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
projectUris.add( ProjectUri.PARENT );
projectQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
}
public Set<Project> getAllProjects()
throws IOException
{
Set<Project> projects = new HashSet<Project>();
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
result = tupleQuery.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
String groupId = set.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString();
String version = set.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString();
String artifactId = set.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString();
String artifactType =
set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString();
String classifier = null;
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
classifier = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() ).getValue().toString();
}
// Project project = getProjectFor( groupId, artifactId, version, artifactType, null );
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
projects.add( getProjectFor( groupId, artifactId, version, artifactType, classifier ) );
}
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-000: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-001: Message = " + e.getMessage() );
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-002: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
return projects;
}
public void setRdfRepository( Repository repository )
{
this.rdfRepository = repository;
}
public boolean openConnection()
{
try
{
repositoryConnection = rdfRepository.getConnection();
repositoryConnection.setAutoCommit( false );
}
catch ( RepositoryException e )
{
return false;
}
return true;
}
public boolean closeConnection()
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.commit();
repositoryConnection.close();
}
catch ( RepositoryException e )
{
return false;
}
}
return true;
}
public void removeProjectFor( String groupId, String artifactId, String version, String artifactType )
throws IOException
{
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id = valueFactory.createURI( groupId + ":" + artifactId + ":" + version + ":" + artifactType );
try
{
repositoryConnection.remove( repositoryConnection.getStatements( id, null, null, true ) );
}
catch ( RepositoryException e )
{
throw new IOException( e.getMessage() );
}
}
public Project getProjectFor( String groupId, String artifactId, String version, String artifactType,
String publicKeyTokenId )
throws IOException
{
long startTime = System.currentTimeMillis();
ValueFactory valueFactory = rdfRepository.getValueFactory();
ProjectDependency project = new ProjectDependency();
project.setArtifactId( artifactId );
project.setGroupId( groupId );
project.setVersion( version );
project.setArtifactType( artifactType );
project.setPublicKeyTokenId( publicKeyTokenId );
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
tupleQuery.setBinding( ProjectUri.GROUP_ID.getObjectBinding(), valueFactory.createLiteral( groupId ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_ID.getObjectBinding(), valueFactory.createLiteral( artifactId ) );
tupleQuery.setBinding( ProjectUri.VERSION.getObjectBinding(), valueFactory.createLiteral( version ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding(),
valueFactory.createLiteral( artifactType ) );
if ( publicKeyTokenId != null )
{
tupleQuery.setBinding( ProjectUri.CLASSIFIER.getObjectBinding(),
valueFactory.createLiteral( publicKeyTokenId ) );
project.setPublicKeyTokenId( publicKeyTokenId.replace( ":", "" ) );
}
result = tupleQuery.evaluate();
if ( !result.hasNext() )
{
//if ( artifactType != null && ArtifactTypeHelper.isDotnetAnyGac( artifactType ) )
if ( artifactType != null )
{
Artifact artifact = createArtifactFrom( project, artifactFactory );
if ( !artifact.getFile().exists() )
{
throw new IOException( "NPANDAY-180-123: Could not find GAC assembly: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = "
+ artifactType + ", File Path = " + artifact.getFile().getAbsolutePath() );
}
project.setResolved( true );
return project;
}
throw new IOException( "NPANDAY-180-124: Could not find the project: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = " + artifactType );
}
while ( result.hasNext() )
{
BindingSet set = result.next();
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
if ( set.hasBinding( ProjectUri.IS_RESOLVED.getObjectBinding() )
&& set.getBinding( ProjectUri.IS_RESOLVED.getObjectBinding() ).getValue().toString().equalsIgnoreCase(
"true" ) )
{
project.setResolved( true );
}
project.setArtifactType( set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
/*
* if ( set.hasBinding( ProjectUri.PARENT.getObjectBinding() ) ) { String pid = set.getBinding(
* ProjectUri.PARENT.getObjectBinding() ).getValue().toString(); String[] tokens = pid.split( "[:]" );
* Project parentProject = getProjectFor( tokens[0], tokens[1], tokens[2], null, null );
* project.setParentProject( parentProject ); }
*/
if ( set.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.DEPENDENCY.getObjectBinding() );
addDependenciesToProject( project, repositoryConnection, binding.getValue() );
}
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
addClassifiersToProject( project, repositoryConnection, binding.getValue() );
}
}
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-005: Message = " + e.getMessage() );
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-006: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-007: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
// TODO: If has parent, then need to modify dependencies, etc of returned project
logger.finest( "NPANDAY-180-008: ProjectDao.GetProjectFor - Artifact Id = " + project.getArtifactId()
+ ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = " + getProjectForCounter++ );
return project;
}
public Project getProjectFor( MavenProject mavenProject )
throws IOException
{
return getProjectFor( mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion(),
mavenProject.getArtifact().getType(), mavenProject.getArtifact().getClassifier() );
}
public void storeProject( Project project, File localRepository, List<ArtifactRepository> artifactRepositories )
throws IOException
{
}
/**
* Generates the system path for gac dependencies.
*/
private String generateDependencySystemPath( ProjectDependency projectDependency )
{
return new File( System.getenv( "SystemRoot" ), "/assembly/"
+ projectDependency.getArtifactType().toUpperCase() + "/" + projectDependency.getArtifactId() + "/"
+ projectDependency.getVersion() + "__" + projectDependency.getPublicKeyTokenId() + "/"
+ projectDependency.getArtifactId() + ".dll" ).getAbsolutePath();
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
return storeProjectAndResolveDependencies( project, localRepository, artifactRepositories,
new HashMap<String, Set<Artifact>>() );
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories,
Map<String, Set<Artifact>> cache )
throws IOException, IllegalArgumentException
{
String key = getKey( project );
if ( cache.containsKey( key ) )
{
return cache.get( key );
}
long startTime = System.currentTimeMillis();
String snapshotVersion;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories, cache ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
Artifact assembly = createArtifactFrom( projectDependency, artifactFactory );
snapshotVersion = null;
logger.info( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File dependencyFile = PathUtil.getDotNetArtifact( assembly , localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
//we have already set file for the assembly above (in createArtifactFrom) so we do not need re-resovle it
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
if (assembly.getFile().exists())
{
projectDependency.setSystemPath( assembly.getFile().getAbsolutePath());
projectDependency.setResolved( true );
assembly.setResolved( true );
}
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
// re-resolve snapshots
if ( !assembly.isSnapshot() )
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
projectDependency = (ProjectDependency) dep;
artifactDependencies.add( assembly );
Set<Artifact> deps = this.storeProjectAndResolveDependencies( projectDependency,
localRepository,
artifactRepositories,
cache );
artifactDependencies.addAll( deps );
}
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
logger.finest("NPANDAY-180-055: dependency:" + projectDependency.getClass());
logger.finest("NPANDAY-180-056: dependency:" + assembly.getClass());
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
logger.finest( "NPANDAY-180-016: set file....");
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
if( model.getArtifactId().equals( projectDependency.getArtifactId() ) && projectDependency.isResolved() )
{
modelDependencies.add( model );
}
}
}
logger.finest( "NPANDAY-180-019: set file...");
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File dotnetFile = PathUtil.getDotNetArtifact( assembly , localRepository );
logger.info( "NPANDAY-180-018: Not found in local repository, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed Path Check = " + dotnetFile.getAbsolutePath());
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ) || !dotnetFile.exists() )// TODO: Generalize to any attached artifact
{
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
projectDependency.setResolved( true );
if ( assembly != null && assembly.getFile().exists() )
{
dotnetFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), dotnetFile );
assembly.setFile( dotnetFile );
}
}
catch ( ArtifactNotFoundException e )
{
logger.log(Level.SEVERE, "NPANDAY-180-0201: Error resolving artifact. Reason:", e);
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.log( Level.SEVERE, "NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage(), e );
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
Project projectModel = ProjectFactory.createProjectFrom( model, null );
artifactDependencies.addAll( storeProjectAndResolveDependencies( projectModel, localRepository,
artifactRepositories, cache ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
cache.put( key, artifactDependencies );
return artifactDependencies;
}
private String getKey( Project project )
{
return project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion();
}
public Set<Artifact> storeModelAndResolveDependencies( Model model, File pomFileDirectory,
File localArtifactRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException
{
return storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model, pomFileDirectory ),
localArtifactRepository, artifactRepositories );
}
public String getClassName()
{
return className;
}
public String getID()
{
return id;
}
public void init( Object dataStoreObject, String id, String className )
throws IllegalArgumentException
{
if ( dataStoreObject == null || !( dataStoreObject instanceof org.openrdf.repository.Repository ) )
{
throw new IllegalArgumentException(
"NPANDAY-180-023: Must initialize with an instance of org.openrdf.repository.Repository" );
}
this.id = id;
this.className = className;
this.rdfRepository = (org.openrdf.repository.Repository) dataStoreObject;
}
public void setRepositoryRegistry( RepositoryRegistry repositoryRegistry )
{
}
protected void initForUnitTest( Object dataStoreObject, String id, String className,
ArtifactResolver artifactResolver, ArtifactFactory artifactFactory )
{
this.init( dataStoreObject, id, className );
init( artifactFactory, artifactResolver );
}
private void addClassifiersToProject( Project project, RepositoryConnection repositoryConnection,
Value classifierUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
String query = "SELECT * FROM {x} p {y}";
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, query );
tq.setBinding( "x", classifierUri );
TupleQueryResult result = tq.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
for ( Iterator<Binding> i = set.iterator(); i.hasNext(); )
{
Binding binding = i.next();
if ( binding.getValue().toString().startsWith( "http://maven.apache.org/artifact/requirement" ) )
{
try
{
project.addRequirement( Requirement.Factory.createDefaultRequirement(
new java.net.URI(
binding.getValue().toString() ),
set.getValue( "y" ).toString() ) );
}
catch ( URISyntaxException e )
{
e.printStackTrace();
}
}
}
}
}
private void addDependenciesToProject( Project project, RepositoryConnection repositoryConnection,
Value dependencyUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, dependencyQuery );
tq.setBinding( "x", dependencyUri );
TupleQueryResult dependencyResult = tq.evaluate();
try
{
while ( dependencyResult.hasNext() )
{
ProjectDependency projectDependency = new ProjectDependency();
BindingSet bs = dependencyResult.next();
projectDependency.setGroupId( bs.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactId( bs.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setVersion( bs.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactType( bs.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
Binding classifierBinding = bs.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
if ( classifierBinding != null )
{
projectDependency.setPublicKeyTokenId( classifierBinding.getValue().toString().replace( ":", "" ) );
}
project.addProjectDependency( projectDependency );
if ( bs.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
addDependenciesToProject( projectDependency, repositoryConnection,
bs.getValue( ProjectUri.DEPENDENCY.getObjectBinding() ) );
}
}
}
finally
{
dependencyResult.close();
}
}
private String constructQueryFragmentFor( String subject, List<ProjectUri> projectUris )
{
// ProjectUri nonOptionalUri = this.getNonOptionalUriFrom( projectUris );
// projectUris.remove( nonOptionalUri );
StringBuffer buffer = new StringBuffer();
buffer.append( subject );
for ( Iterator<ProjectUri> i = projectUris.iterator(); i.hasNext(); )
{
ProjectUri projectUri = i.next();
buffer.append( " " );
if ( projectUri.isOptional() )
{
buffer.append( "[" );
}
buffer.append( "<" ).append( projectUri.getPredicate() ).append( "> {" ).append(
projectUri.getObjectBinding() ).append(
"}" );
if ( projectUri.isOptional() )
{
buffer.append( "]" );
}
if ( i.hasNext() )
{
buffer.append( ";" );
}
}
return buffer.toString();
}
private ProjectUri getNonOptionalUriFrom( List<ProjectUri> projectUris )
{
for ( ProjectUri projectUri : projectUris )
{
if ( !projectUri.isOptional() )
{
return projectUri;
}
}
return null;
}
// TODO: move generateInteropDll, getInteropParameters, getTempDirectory, and execute methods to another class
private String generateInteropDll( String name, String classifier )
throws IOException
{
File tmpDir;
String comReferenceAbsolutePath = "";
try
{
tmpDir = getTempDirectory();
}
catch ( IOException e )
{
throw new IOException( "Unable to create temporary directory" );
}
try
{
comReferenceAbsolutePath = resolveComReferencePath( name, classifier );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
String interopAbsolutePath = tmpDir.getAbsolutePath() + File.separator + "Interop." + name + ".dll";
List<String> params = getInteropParameters( interopAbsolutePath, comReferenceAbsolutePath, name );
try
{
execute( "tlbimp", params );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
return interopAbsolutePath;
}
private String resolveComReferencePath( String name, String classifier )
throws Exception
{
String[] classTokens = classifier.split( "}" );
classTokens[1] = classTokens[1].replace( "-", "\\" );
String newClassifier = classTokens[0] + "}" + classTokens[1];
String registryPath = "HKEY_CLASSES_ROOT\\TypeLib\\" + newClassifier + "\\win32\\";
int lineNoOfPath = 1;
List<String> parameters = new ArrayList<String>();
parameters.add( "query" );
parameters.add( registryPath );
parameters.add( "/ve" );
StreamConsumer outConsumer = new StreamConsumerImpl();
StreamConsumer errorConsumer = new StreamConsumerImpl();
try
{
// TODO: investigate why outConsumer ignores newline
execute( "reg", parameters, outConsumer, errorConsumer );
}
catch ( Exception e )
{
throw new Exception( "Cannot find information of [" + name
+ "] ActiveX component in your system, you need to install this component first to continue." );
}
// parse outConsumer
String out = outConsumer.toString();
String tokens[] = out.split( "\n" );
String lineResult = "";
String[] result;
if ( tokens.length >= lineNoOfPath - 1 )
{
lineResult = tokens[lineNoOfPath - 1];
}
result = lineResult.split( "REG_SZ" );
if ( result.length > 1 )
{
return result[1].trim();
}
return null;
}
private List<String> readPomAttribute( String pomFileLoc, String tag )
{
List<String> attributes = new ArrayList<String>();
try
{
File file = new File( pomFileLoc );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( file );
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName( tag );
for ( int s = 0; s < nodeLst.getLength(); s++ )
{
Node currentNode = nodeLst.item( s );
NodeList childrenList = currentNode.getChildNodes();
for ( int i = 0; i < childrenList.getLength(); i++ )
{
Node child = childrenList.item( i );
attributes.add( child.getNodeValue() );
}
}
}
catch ( Exception e )
{
}
return attributes;
}
private List<String> getInteropParameters( String interopAbsolutePath, String comRerefenceAbsolutePath,
String namespace )
{
List<String> parameters = new ArrayList<String>();
parameters.add( comRerefenceAbsolutePath );
parameters.add( "/out:" + interopAbsolutePath );
parameters.add( "/namespace:" + namespace );
try
{
// beginning code for checking of strong name key or signing of projects
String key = "";
String keyfile = "";
String currentWorkingDir = System.getProperty( "user.dir" );
// Check if Parent pom
List<String> modules = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "module" );
if ( !modules.isEmpty() )
{
// check if there is a matching dependency with the namespace
for ( String child : modules )
{
// check each module pom file if there is existing keyfile
String tempDir = currentWorkingDir + File.separator + child;
try
{
List<String> keyfiles = readPomAttribute( tempDir + "\\pom.xml", "keyfile" );
if ( keyfiles.get( 0 ) != null )
{
// PROBLEM WITH MULTIMODULES
boolean hasComRef = false;
List<String> dependencies = readPomAttribute( tempDir + "\\pom.xml", "groupId" );
for ( String item : dependencies )
{
if ( item.equals( namespace ) )
{
hasComRef = true;
break;
}
}
if ( hasComRef )
{
key = keyfiles.get( 0 );
currentWorkingDir = tempDir;
}
}
}
catch ( Exception e )
{
}
}
}
else
{
// not a parent pom, so read project pom file for keyfile value
List<String> keyfiles = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "keyfile" );
key = keyfiles.get( 0 );
}
if ( key != "" )
{
keyfile = currentWorkingDir + File.separator + key;
parameters.add( "/keyfile:" + keyfile );
}
// end code for checking of strong name key or signing of projects
}
catch ( Exception ex )
{
}
return parameters;
}
private File getTempDirectory()
throws IOException
{
File tempFile = File.createTempFile( "interop-dll-", "" );
File tmpDir = new File( tempFile.getParentFile(), tempFile.getName() );
tempFile.delete();
tmpDir.mkdir();
return tmpDir;
}
// can't use dotnet-executable due to cyclic dependency.
private void execute( String executable, List<String> commands )
throws Exception
{
execute( executable, commands, null, null );
}
private void execute( String executable, List<String> commands, StreamConsumer systemOut, StreamConsumer systemError )
throws Exception
{
int result = 0;
Commandline commandline = new Commandline();
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()] ) );
try
{
result = CommandLineUtils.executeCommandLine( commandline, systemOut, systemError );
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline + ", Result = "
+ result );
if ( result != 0 )
{
throw new Exception( "NPANDAY-040-001: Could not execute: Command = " + commandline.toString()
+ ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new Exception( "NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
/**
* Creates an artifact using information from the specified project dependency.
*
* @param projectDependency a project dependency to use as the source of the returned artifact
* @param artifactFactory artifact factory used to create the artifact
* @return an artifact using information from the specified project dependency
*/
private static Artifact createArtifactFrom( ProjectDependency projectDependency, ArtifactFactory artifactFactory )
{
String groupId = projectDependency.getGroupId();
String artifactId = projectDependency.getArtifactId();
String version = projectDependency.getVersion();
String artifactType = projectDependency.getArtifactType();
String scope = ( projectDependency.getScope() == null ) ? Artifact.SCOPE_COMPILE : projectDependency.getScope();
String publicKeyTokenId = projectDependency.getPublicKeyTokenId();
if ( groupId == null )
{
logger.warning( "NPANDAY-180-001: Project Group ID is missing" );
}
if ( artifactId == null )
{
logger.warning( "NPANDAY-180-002: Project Artifact ID is missing: Group Id = " + groupId );
}
if ( version == null )
{
logger.warning( "NPANDAY-180-003: Project Version is missing: Group Id = " + groupId +
", Artifact Id = " + artifactId );
}
if ( artifactType == null )
{
logger.warning( "NPANDAY-180-004: Project Artifact Type is missing: Group Id" + groupId +
", Artifact Id = " + artifactId + ", Version = " + version );
}
Artifact assembly = artifactFactory.createDependencyArtifact( groupId, artifactId,
VersionRange.createFromVersion( version ),
artifactType, publicKeyTokenId, scope,
null );
//using PathUtil
File artifactFile = null;
if (ArtifactTypeHelper.isDotnetAnyGac( artifactType ))
{
if (!ArtifactTypeHelper.isDotnet4Gac(artifactType))
{
artifactFile = PathUtil.getGlobalAssemblyCacheFileFor( assembly, new File("C:\\WINDOWS\\assembly\\") );
}
else
{
artifactFile = PathUtil.getGACFile4Artifact(assembly);
}
}
else
{
artifactFile = PathUtil.getUserAssemblyCacheFileFor( assembly, new File( System.getProperty( "user.home" ),
File.separator + ".m2" + File.separator + "repository") );
}
assembly.setFile( artifactFile );
return assembly;
}
/**
* TODO: refactor this to another class and all methods concerning com_reference StreamConsumer instance that
* buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
}
| [NPANDAY-351] NPanday does not respect the configured repository in the pom
Added artifact resolver to look up to remote repos for the dependencies that were skipped and could not be resolved from the local repositories
git-svn-id: ee144a4ada4e65570a65b3ba2a4ac9d4eedc8fa4@1045023 13f79535-47bb-0310-9956-ffa450edef68
| components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java | [NPANDAY-351] NPanday does not respect the configured repository in the pom | <ide><path>omponents/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
<ide>
<ide> snapshotVersion = null;
<ide>
<add> if(!assembly.getFile().exists())
<add> {
<add>
<add> try
<add> {
<add> ArtifactRepository localArtifactRepository =
<add> new DefaultArtifactRepository( "local", "file://" + localRepository,
<add> new DefaultRepositoryLayout() );
<add>
<add> artifactResolver.resolve( assembly, artifactRepositories,
<add> localArtifactRepository );
<add> }
<add> catch ( ArtifactNotFoundException e )
<add> {
<add> logger.info( "NPANDAY-181-121: Problem in resolving assembly: " + assembly.toString()
<add> + ", Message = " + e.getMessage() );
<add> }
<add> catch ( ArtifactResolutionException e )
<add> {
<add> logger.info( "NPANDAY-181-122: Problem in resolving assembly: " + assembly.toString()
<add> + ", Message = " + e.getMessage() );
<add> }
<add> }
<add>
<ide> logger.info( "NPANDAY-180-011: Project Dependency: Artifact ID = "
<ide> + projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
<ide> + ", Version = " + projectDependency.getVersion() + ", Artifact Type = " |
|
JavaScript | mit | 1cc9ab7900feb1e2f7e0c9d8aa515d021ea7c56d | 0 | codepolitan/material-demo,codepolitan/material-demo | material.js | import Button from 'material/src/button'
import Calendar from 'material/src/calendar'
import Card from 'material/src/card'
import Component from 'material/src/component'
import Container from 'material/src/container'
import Checkbox from 'material/src/checkbox'
import Dialog from 'material/src/dialog'
import Divider from 'material/src/divider'
import Drawer from 'material/src/drawer'
import Form from 'material/src/form'
import Image from 'material/src/image'
import Item from 'material/src/item'
import Layout from 'material/src/layout'
import Layout2 from 'material/src/layout2'
import List from 'material/src/list'
import Menu from 'material/src/menu'
import Slider from 'material/src/slider'
import Switch from 'material/src/switch'
import Text from 'material/src/text'
import Textfield from 'material/src/textfield'
import Toolbar from 'material/src/toolbar'
export {
Button,
Calendar,
Card,
Checkbox,
Component,
Container,
Dialog,
Divider,
Drawer,
Form,
Image,
Item,
Layout,
Layout2,
List,
Menu,
Slider,
Switch,
Text,
Textfield,
Toolbar
}
| delete material.js
| material.js | delete material.js | <ide><path>aterial.js
<del>import Button from 'material/src/button'
<del>import Calendar from 'material/src/calendar'
<del>import Card from 'material/src/card'
<del>import Component from 'material/src/component'
<del>import Container from 'material/src/container'
<del>import Checkbox from 'material/src/checkbox'
<del>import Dialog from 'material/src/dialog'
<del>import Divider from 'material/src/divider'
<del>import Drawer from 'material/src/drawer'
<del>import Form from 'material/src/form'
<del>import Image from 'material/src/image'
<del>import Item from 'material/src/item'
<del>import Layout from 'material/src/layout'
<del>import Layout2 from 'material/src/layout2'
<del>import List from 'material/src/list'
<del>import Menu from 'material/src/menu'
<del>import Slider from 'material/src/slider'
<del>import Switch from 'material/src/switch'
<del>import Text from 'material/src/text'
<del>import Textfield from 'material/src/textfield'
<del>import Toolbar from 'material/src/toolbar'
<del>
<del>export {
<del> Button,
<del> Calendar,
<del> Card,
<del> Checkbox,
<del> Component,
<del> Container,
<del> Dialog,
<del> Divider,
<del> Drawer,
<del> Form,
<del> Image,
<del> Item,
<del> Layout,
<del> Layout2,
<del> List,
<del> Menu,
<del> Slider,
<del> Switch,
<del> Text,
<del> Textfield,
<del> Toolbar
<del>} |
||
Java | apache-2.0 | 5c37ec3347c4bf1b6e0267c8451beac0ef63358d | 0 | GoogleCloudPlatform/cloud-sql-jdbc-socket-factory,GoogleCloudPlatform/cloud-sql-jdbc-socket-factory | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.sql.mysql;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sqladmin.SQLAdmin;
import com.google.api.services.sqladmin.SQLAdmin.Builder;
import com.google.api.services.sqladmin.SQLAdminScopes;
import com.google.api.services.sqladmin.model.DatabaseInstance;
import com.google.api.services.sqladmin.model.SslCert;
import com.google.api.services.sqladmin.model.SslCertsCreateEphemeralRequest;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.RateLimiter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.bind.DatatypeConverter;
/**
* Factory responsible for obtaining an ephemeral certificate, if necessary, and establishing a
* secure connecting to a Cloud SQL instance.
*
* <p>This class should not be used directly, but only through the JDBC driver specific
* {@code SocketFactory} implementations.
*
* <p>The API of this class is subject to change without notice.
*/
public class SslSocketFactory {
private static final Logger logger = Logger.getLogger(SslSocketFactory.class.getName());
static final String ADMIN_API_NOT_ENABLED_REASON = "accessNotConfigured";
static final String INSTANCE_NOT_AUTHORIZED_REASON = "notAuthorized";
// Test properties, not for end-user use. May be changed or removed without notice.
private static final String CREDENTIAL_FACTORY_PROPERTY = "_CLOUD_SQL_API_CREDENTIAL_FACTORY";
private static final String API_ROOT_URL_PROPERTY = "_CLOUD_SQL_API_ROOT_URL";
private static final String API_SERVICE_PATH_PROPERTY = "_CLOUD_SQL_API_SERVICE_PATH";
private static final int DEFAULT_SERVER_PROXY_PORT = 3307;
private static final int RSA_KEY_SIZE = 2048;
private static SslSocketFactory sslSocketFactory;
private final CertificateFactory certificateFactory;
private final Clock clock;
private final KeyPair localKeyPair;
private final Credential credential;
private final Map<String, InstanceLookupResult> cache = new HashMap<>();
private final SQLAdmin adminApi;
private final int serverProxyPort;
// Protection from attempting to renew ephemeral certificate too often in case of handshake
// error. Allow forced renewal once a minute.
private final RateLimiter forcedRenewRateLimiter = RateLimiter.create(1.0 / 60.0);
@VisibleForTesting
SslSocketFactory(
Clock clock,
KeyPair localKeyPair,
Credential credential,
SQLAdmin adminApi,
int serverProxyPort) {
try {
this.certificateFactory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new RuntimeException("X509 implementation not available", e);
}
this.clock = clock;
this.localKeyPair = localKeyPair;
this.credential = credential;
this.adminApi = adminApi;
this.serverProxyPort = serverProxyPort;
}
public static synchronized SslSocketFactory getInstance() {
if (sslSocketFactory == null) {
logger.info("First Cloud SQL connection, generating RSA key pair.");
KeyPair keyPair = generateRsaKeyPair();
CredentialFactory credentialFactory;
if (System.getProperty(CREDENTIAL_FACTORY_PROPERTY) != null) {
logTestPropertyWarning(CREDENTIAL_FACTORY_PROPERTY);
try {
credentialFactory =
(CredentialFactory)
Class.forName(System.getProperty(CREDENTIAL_FACTORY_PROPERTY))
.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
credentialFactory = new ApplicationDefaultCredentialFactory();
}
Credential credential = credentialFactory.create();
SQLAdmin adminApi = createAdminApiClient(credential);
sslSocketFactory =
new SslSocketFactory(
new Clock(), keyPair, credential, adminApi, DEFAULT_SERVER_PROXY_PORT);
}
return sslSocketFactory;
}
// TODO(berezv): separate creating socket and performing connection to make it easier to test
public Socket create(String instanceName) throws IOException {
try {
return createAndConfigureSocket(instanceName, CertificateCaching.USE_CACHE);
} catch (SSLHandshakeException e) {
logger.warning(
String.format(
"SSL handshake failed for Cloud SQL instance [%s], "
+ "retrying with new certificate.\n%s",
instanceName,
Throwables.getStackTraceAsString(e)));
if (!forcedRenewRateLimiter.tryAcquire()) {
logger.warning(
String.format(
"Renewing too often, rate limiting certificate renewal for Cloud SQL "
+ "instance [%s].",
instanceName));
forcedRenewRateLimiter.acquire();
}
return createAndConfigureSocket(instanceName, CertificateCaching.BYPASS_CACHE);
}
}
private static void logTestPropertyWarning(String property) {
logger.warning(
String.format(
"%s is a test property and may be changed or removed in a future version without "
+ "notice.",
property));
}
private SSLSocket createAndConfigureSocket(
String instanceName, CertificateCaching certificateCaching) throws IOException {
InstanceSslInfo instanceSslInfo = getInstanceSslInfo(instanceName, certificateCaching);
String ipAddress = instanceSslInfo.getInstanceIpAddress();
logger.info(
String.format(
"Connecting to Cloud SQL instance [%s] on IP [%s].", instanceName, ipAddress));
SSLSocket sslSocket =
(SSLSocket)
instanceSslInfo.getSslSocketFactory().createSocket(ipAddress, serverProxyPort);
// TODO(berezv): Support all socket related options listed here:
// https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
// TODO(berezv): Make sure we have appropriate timeout for establishing connection.
sslSocket.setKeepAlive(true);
sslSocket.setTcpNoDelay(true);
sslSocket.startHandshake();
return sslSocket;
}
// TODO(berezv): synchronize per instance, instead of globally
@VisibleForTesting
synchronized InstanceSslInfo getInstanceSslInfo(
String instanceConnectionString, CertificateCaching certificateCaching) {
if (certificateCaching.equals(CertificateCaching.USE_CACHE)) {
InstanceLookupResult lookupResult = cache.get(instanceConnectionString);
if (lookupResult != null) {
if (!lookupResult.isSuccessful()
&& (clock.now() - lookupResult.getLastFailureMillis()) < 60 * 1000) {
logger.warning(
"Re-throwing cached exception due to attempt to refresh instance information too "
+ "soon after error.");
throw lookupResult.getException().get();
} else if (lookupResult.isSuccessful()) {
InstanceSslInfo details = lookupResult.getInstanceSslInfo().get();
// Check if the cached certificate is still valid.
if (details != null) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(clock.now());
calendar.add(Calendar.MINUTE, 5);
try {
details.getEphemeralCertificate().checkValidity(calendar.getTime());
} catch (CertificateException e) {
logger.info(
String.format(
"Ephemeral certificate for Cloud SQL instance [%s] is about to expire, "
+ "obtaining new one.",
instanceConnectionString));
details = null;
}
}
if (details != null) {
return details;
}
}
}
}
String invalidInstanceError =
String.format(
"Invalid Cloud SQL instance [%s], expected value in form [project:region:name].",
instanceConnectionString);
int beforeNameIndex = instanceConnectionString.lastIndexOf(':');
if (beforeNameIndex <= 0) {
throw new IllegalArgumentException(invalidInstanceError);
}
int beforeRegionIndex = instanceConnectionString.lastIndexOf(':', beforeNameIndex - 1);
if (beforeRegionIndex <= 0) {
throw new IllegalArgumentException(invalidInstanceError);
}
String projectId = instanceConnectionString.substring(0, beforeRegionIndex);
String region = instanceConnectionString.substring(beforeRegionIndex + 1, beforeNameIndex);
String instanceName = instanceConnectionString.substring(beforeNameIndex + 1);
InstanceLookupResult instanceLookupResult;
InstanceSslInfo details;
try {
details = fetchInstanceSslInfo(instanceConnectionString, projectId, region, instanceName);
instanceLookupResult = new InstanceLookupResult(details);
cache.put(instanceConnectionString, instanceLookupResult);
} catch (RuntimeException e) {
instanceLookupResult = new InstanceLookupResult(e);
cache.put(instanceConnectionString, instanceLookupResult);
throw e;
}
return details;
}
private InstanceSslInfo fetchInstanceSslInfo(
String instanceConnectionString, String projectId, String region, String instanceName) {
logger.info(
String.format(
"Obtaining ephemeral certificate for Cloud SQL instance [%s].",
instanceConnectionString));
DatabaseInstance instance =
obtainInstanceMetadata(adminApi, instanceConnectionString, projectId, instanceName);
if (instance.getIpAddresses().isEmpty()) {
throw
new RuntimeException(
String.format(
"Cloud SQL instance [%s] does not have any external IP addresses",
instanceConnectionString));
}
if (!instance.getRegion().equals(region)) {
throw
new IllegalArgumentException(
String.format(
"Incorrect region value [%s] for Cloud SQL instance [%s], should be [%s]",
region,
instanceConnectionString,
instance.getRegion()));
}
X509Certificate ephemeralCertificate =
obtainEphemeralCertificate(adminApi, instanceConnectionString, projectId, instanceName);
Certificate instanceCaCertificate;
try {
instanceCaCertificate =
certificateFactory.generateCertificate(
new ByteArrayInputStream(
instance.getServerCaCert().getCert().getBytes(StandardCharsets.UTF_8)));
} catch (CertificateException e) {
throw
new RuntimeException(
String.format(
"Unable to parse certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
SSLContext sslContext = createSslContext(ephemeralCertificate, instanceCaCertificate);
return
new InstanceSslInfo(
instance.getIpAddresses().get(0).getIpAddress(),
ephemeralCertificate,
sslContext.getSocketFactory());
}
private SSLContext createSslContext(
Certificate ephemeralCertificate, Certificate instanceCaCertificate) {
KeyStore authKeyStore;
try {
authKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
authKeyStore.load(null, null);
KeyStore.PrivateKeyEntry pk =
new KeyStore.PrivateKeyEntry(
localKeyPair.getPrivate(), new Certificate[]{ephemeralCertificate});
authKeyStore.setEntry("ephemeral", pk, new PasswordProtection(new char[0]));
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("There was a problem initializing the auth key store", e);
}
KeyStore trustKeyStore;
try {
trustKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustKeyStore.load(null, null);
trustKeyStore.setCertificateEntry("instance", instanceCaCertificate);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("There was a problem initializing the trust key store", e);
}
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(authKeyStore, new char[0]);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X.509");
tmf.init(trustKeyStore);
sslContext.init(
keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return sslContext;
} catch (GeneralSecurityException e) {
throw new RuntimeException("There was a problem initializing the SSL context", e);
}
}
private DatabaseInstance obtainInstanceMetadata(
SQLAdmin adminApi, String instanceConnectionString, String projectId, String instanceName) {
DatabaseInstance instance;
try {
instance = adminApi.instances().get(projectId, instanceName).execute();
} catch (GoogleJsonResponseException e) {
if (e.getDetails() == null || e.getDetails().getErrors().isEmpty()) {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
String reason = e.getDetails().getErrors().get(0).getReason();
if (ADMIN_API_NOT_ENABLED_REASON.equals(reason)) {
String apiLink =
"https://console.cloud.google.com/apis/api/sqladmin/overview?project=" + projectId;
throw
new RuntimeException(
String.format(
"The Google Cloud SQL API is not enabled for project [%s]. Please "
+ "use the Google Developers Console to enable it: %s",
projectId,
apiLink));
} else if (INSTANCE_NOT_AUTHORIZED_REASON.equals(reason)) {
// TODO(berezv): check if this works on Compute Engine / App Engine
String who = "you are";
if (getCredentialServiceAccount(credential) != null) {
who = "[" + getCredentialServiceAccount(credential) + "] is";
}
throw
new RuntimeException(
String.format(
"Cloud SQL Instance [%s] does not exist or %s not authorized to "
+ "access it. Please check the instance and project names to make "
+ "sure they are correct.",
instanceConnectionString,
who));
} else {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
} catch (IOException e) {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
if (!instance.getBackendType().equals("SECOND_GEN")) {
throw
new IllegalArgumentException(
"This client only supports connections to Second Generation Cloud SQL "
+ "instances");
}
return instance;
}
private X509Certificate obtainEphemeralCertificate(
SQLAdmin adminApi, String instanceConnectionString, String projectId, String instanceName) {
StringBuilder publicKeyPemBuilder = new StringBuilder();
publicKeyPemBuilder.append("-----BEGIN RSA PUBLIC KEY-----\n");
publicKeyPemBuilder.append(
DatatypeConverter.printBase64Binary(localKeyPair.getPublic().getEncoded())
.replaceAll("(.{64})", "$1\n"));
publicKeyPemBuilder.append("\n");
publicKeyPemBuilder.append("-----END RSA PUBLIC KEY-----\n");
SslCertsCreateEphemeralRequest req = new SslCertsCreateEphemeralRequest();
req.setPublicKey(publicKeyPemBuilder.toString());
SslCert response;
try {
response = adminApi.sslCerts().createEphemeral(projectId, instanceName, req).execute();
} catch (GoogleJsonResponseException e) {
if (e.getDetails() == null || e.getDetails().getErrors().isEmpty()) {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
String reason = e.getDetails().getErrors().get(0).getReason();
if (INSTANCE_NOT_AUTHORIZED_REASON.equals(reason)) {
String who = "you have";
if (getCredentialServiceAccount(credential) != null) {
who = "[" + getCredentialServiceAccount(credential) + "] has";
}
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL Instance [%s]. "
+ "Make sure %s Editor or Owner role on the project.",
instanceConnectionString,
who));
} else {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
} catch (IOException e) {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
try {
return
(X509Certificate) certificateFactory.generateCertificate(
new ByteArrayInputStream(response.getCert().getBytes(StandardCharsets.UTF_8)));
} catch (CertificateException e) {
throw
new RuntimeException(
String.format(
"Unable to parse ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
}
@Nullable
private String getCredentialServiceAccount(Credential credential) {
return
credential instanceof GoogleCredential
? ((GoogleCredential) credential).getServiceAccountId()
: null;
}
private static SQLAdmin createAdminApiClient(Credential credential) {
HttpTransport httpTransport;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("Unable to initialize HTTP transport", e);
}
String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY);
String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY);
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
SQLAdmin.Builder adminApiBuilder =
new Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Cloud SQL Java Socket Factory");
if (rootUrl != null) {
logTestPropertyWarning(API_ROOT_URL_PROPERTY);
adminApiBuilder.setRootUrl(rootUrl);
}
if (servicePath != null) {
logTestPropertyWarning(API_SERVICE_PATH_PROPERTY);
adminApiBuilder.setServicePath(servicePath);
}
return adminApiBuilder.build();
}
private static class ApplicationDefaultCredentialFactory implements CredentialFactory {
@Override
public Credential create() {
GoogleCredential credential;
try {
credential = GoogleCredential.getApplicationDefault();
} catch (IOException e) {
throw
new RuntimeException(
"Unable to obtain credentials to communicate with the Cloud SQL API", e);
}
if (credential.createScopedRequired()) {
credential = credential.createScoped(
Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN));
}
return credential;
}
}
private static KeyPair generateRsaKeyPair() {
KeyPairGenerator generator;
try {
generator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(
"Unable to initialize Cloud SQL socket factory because no RSA implementation is "
+ "available.");
}
generator.initialize(RSA_KEY_SIZE);
return generator.generateKeyPair();
}
private class InstanceLookupResult {
private final Optional<RuntimeException> exception;
private final long lastFailureMillis;
private final Optional<InstanceSslInfo> instanceSslInfo;
public InstanceLookupResult(RuntimeException exception) {
this.exception = Optional.of(exception);
this.lastFailureMillis = clock.now();
this.instanceSslInfo = Optional.absent();
}
public InstanceLookupResult(InstanceSslInfo instanceSslInfo) {
this.instanceSslInfo = Optional.of(instanceSslInfo);
this.exception = Optional.absent();
this.lastFailureMillis = 0;
}
public boolean isSuccessful() {
return !exception.isPresent();
}
public Optional<InstanceSslInfo> getInstanceSslInfo() {
return instanceSslInfo;
}
public Optional<RuntimeException> getException() {
return exception;
}
public long getLastFailureMillis() {
return lastFailureMillis;
}
}
private static class InstanceSslInfo {
private final String instanceIpAddress;
private final X509Certificate ephemeralCertificate;
private final SSLSocketFactory sslSocketFactory;
InstanceSslInfo(
String instanceIpAddress,
X509Certificate ephemeralCertificate,
SSLSocketFactory sslSocketFactory) {
this.instanceIpAddress = instanceIpAddress;
this.ephemeralCertificate = ephemeralCertificate;
this.sslSocketFactory = sslSocketFactory;
}
public String getInstanceIpAddress() {
return instanceIpAddress;
}
public X509Certificate getEphemeralCertificate() {
return ephemeralCertificate;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
}
@VisibleForTesting
enum CertificateCaching {
USE_CACHE,
BYPASS_CACHE
}
static class Clock {
long now() {
return System.currentTimeMillis();
}
}
}
| core/src/main/java/com/google/cloud/sql/mysql/SslSocketFactory.java | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.sql.mysql;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sqladmin.SQLAdmin;
import com.google.api.services.sqladmin.SQLAdmin.Builder;
import com.google.api.services.sqladmin.SQLAdminScopes;
import com.google.api.services.sqladmin.model.DatabaseInstance;
import com.google.api.services.sqladmin.model.SslCert;
import com.google.api.services.sqladmin.model.SslCertsCreateEphemeralRequest;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.RateLimiter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.bind.DatatypeConverter;
/**
* Factory responsible for obtaining an ephemeral certificate, if necessary, and establishing a
* secure connecting to a Cloud SQL instance.
*
* <p>The implementation is separate from {@link SocketFactory} to make this code easier to test.
*/
public class SslSocketFactory {
private static final Logger logger = Logger.getLogger(SslSocketFactory.class.getName());
static final String ADMIN_API_NOT_ENABLED_REASON = "accessNotConfigured";
static final String INSTANCE_NOT_AUTHORIZED_REASON = "notAuthorized";
// Test properties, not for end-user use. May be changed or removed without notice.
private static final String CREDENTIAL_FACTORY_PROPERTY = "_CLOUD_SQL_API_CREDENTIAL_FACTORY";
private static final String API_ROOT_URL_PROPERTY = "_CLOUD_SQL_API_ROOT_URL";
private static final String API_SERVICE_PATH_PROPERTY = "_CLOUD_SQL_API_SERVICE_PATH";
private static final int DEFAULT_SERVER_PROXY_PORT = 3307;
private static final int RSA_KEY_SIZE = 2048;
private static SslSocketFactory sslSocketFactory;
private final CertificateFactory certificateFactory;
private final Clock clock;
private final KeyPair localKeyPair;
private final Credential credential;
private final Map<String, InstanceLookupResult> cache = new HashMap<>();
private final SQLAdmin adminApi;
private final int serverProxyPort;
// Protection from attempting to renew ephemeral certificate too often in case of handshake
// error. Allow forced renewal once a minute.
private final RateLimiter forcedRenewRateLimiter = RateLimiter.create(1.0 / 60.0);
@VisibleForTesting
SslSocketFactory(
Clock clock,
KeyPair localKeyPair,
Credential credential,
SQLAdmin adminApi,
int serverProxyPort) {
try {
this.certificateFactory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new RuntimeException("X509 implementation not available", e);
}
this.clock = clock;
this.localKeyPair = localKeyPair;
this.credential = credential;
this.adminApi = adminApi;
this.serverProxyPort = serverProxyPort;
}
public static synchronized SslSocketFactory getInstance() {
if (sslSocketFactory == null) {
logger.info("First Cloud SQL connection, generating RSA key pair.");
KeyPair keyPair = generateRsaKeyPair();
CredentialFactory credentialFactory;
if (System.getProperty(CREDENTIAL_FACTORY_PROPERTY) != null) {
logTestPropertyWarning(CREDENTIAL_FACTORY_PROPERTY);
try {
credentialFactory =
(CredentialFactory)
Class.forName(System.getProperty(CREDENTIAL_FACTORY_PROPERTY))
.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
credentialFactory = new ApplicationDefaultCredentialFactory();
}
Credential credential = credentialFactory.create();
SQLAdmin adminApi = createAdminApiClient(credential);
sslSocketFactory =
new SslSocketFactory(
new Clock(), keyPair, credential, adminApi, DEFAULT_SERVER_PROXY_PORT);
}
return sslSocketFactory;
}
// TODO(berezv): separate creating socket and performing connection to make it easier to test
public Socket create(String instanceName) throws IOException {
try {
return createAndConfigureSocket(instanceName, CertificateCaching.USE_CACHE);
} catch (SSLHandshakeException e) {
logger.warning(
String.format(
"SSL handshake failed for Cloud SQL instance [%s], "
+ "retrying with new certificate.\n%s",
instanceName,
Throwables.getStackTraceAsString(e)));
if (!forcedRenewRateLimiter.tryAcquire()) {
logger.warning(
String.format(
"Renewing too often, rate limiting certificate renewal for Cloud SQL "
+ "instance [%s].",
instanceName));
forcedRenewRateLimiter.acquire();
}
return createAndConfigureSocket(instanceName, CertificateCaching.BYPASS_CACHE);
}
}
private static void logTestPropertyWarning(String property) {
logger.warning(
String.format(
"%s is a test property and may be changed or removed in a future version without "
+ "notice.",
property));
}
private SSLSocket createAndConfigureSocket(
String instanceName, CertificateCaching certificateCaching) throws IOException {
InstanceSslInfo instanceSslInfo = getInstanceSslInfo(instanceName, certificateCaching);
String ipAddress = instanceSslInfo.getInstanceIpAddress();
logger.info(
String.format(
"Connecting to Cloud SQL instance [%s] on IP [%s].", instanceName, ipAddress));
SSLSocket sslSocket =
(SSLSocket)
instanceSslInfo.getSslSocketFactory().createSocket(ipAddress, serverProxyPort);
// TODO(berezv): Support all socket related options listed here:
// https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
// TODO(berezv): Make sure we have appropriate timeout for establishing connection.
sslSocket.setKeepAlive(true);
sslSocket.setTcpNoDelay(true);
sslSocket.startHandshake();
return sslSocket;
}
// TODO(berezv): synchronize per instance, instead of globally
@VisibleForTesting
synchronized InstanceSslInfo getInstanceSslInfo(
String instanceConnectionString, CertificateCaching certificateCaching) {
if (certificateCaching.equals(CertificateCaching.USE_CACHE)) {
InstanceLookupResult lookupResult = cache.get(instanceConnectionString);
if (lookupResult != null) {
if (!lookupResult.isSuccessful()
&& (clock.now() - lookupResult.getLastFailureMillis()) < 60 * 1000) {
logger.warning(
"Re-throwing cached exception due to attempt to refresh instance information too "
+ "soon after error.");
throw lookupResult.getException().get();
} else if (lookupResult.isSuccessful()) {
InstanceSslInfo details = lookupResult.getInstanceSslInfo().get();
// Check if the cached certificate is still valid.
if (details != null) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(clock.now());
calendar.add(Calendar.MINUTE, 5);
try {
details.getEphemeralCertificate().checkValidity(calendar.getTime());
} catch (CertificateException e) {
logger.info(
String.format(
"Ephemeral certificate for Cloud SQL instance [%s] is about to expire, "
+ "obtaining new one.",
instanceConnectionString));
details = null;
}
}
if (details != null) {
return details;
}
}
}
}
String invalidInstanceError =
String.format(
"Invalid Cloud SQL instance [%s], expected value in form [project:region:name].",
instanceConnectionString);
int beforeNameIndex = instanceConnectionString.lastIndexOf(':');
if (beforeNameIndex <= 0) {
throw new IllegalArgumentException(invalidInstanceError);
}
int beforeRegionIndex = instanceConnectionString.lastIndexOf(':', beforeNameIndex - 1);
if (beforeRegionIndex <= 0) {
throw new IllegalArgumentException(invalidInstanceError);
}
String projectId = instanceConnectionString.substring(0, beforeRegionIndex);
String region = instanceConnectionString.substring(beforeRegionIndex + 1, beforeNameIndex);
String instanceName = instanceConnectionString.substring(beforeNameIndex + 1);
InstanceLookupResult instanceLookupResult;
InstanceSslInfo details;
try {
details = fetchInstanceSslInfo(instanceConnectionString, projectId, region, instanceName);
instanceLookupResult = new InstanceLookupResult(details);
cache.put(instanceConnectionString, instanceLookupResult);
} catch (RuntimeException e) {
instanceLookupResult = new InstanceLookupResult(e);
cache.put(instanceConnectionString, instanceLookupResult);
throw e;
}
return details;
}
private InstanceSslInfo fetchInstanceSslInfo(
String instanceConnectionString, String projectId, String region, String instanceName) {
logger.info(
String.format(
"Obtaining ephemeral certificate for Cloud SQL instance [%s].",
instanceConnectionString));
DatabaseInstance instance =
obtainInstanceMetadata(adminApi, instanceConnectionString, projectId, instanceName);
if (instance.getIpAddresses().isEmpty()) {
throw
new RuntimeException(
String.format(
"Cloud SQL instance [%s] does not have any external IP addresses",
instanceConnectionString));
}
if (!instance.getRegion().equals(region)) {
throw
new IllegalArgumentException(
String.format(
"Incorrect region value [%s] for Cloud SQL instance [%s], should be [%s]",
region,
instanceConnectionString,
instance.getRegion()));
}
X509Certificate ephemeralCertificate =
obtainEphemeralCertificate(adminApi, instanceConnectionString, projectId, instanceName);
Certificate instanceCaCertificate;
try {
instanceCaCertificate =
certificateFactory.generateCertificate(
new ByteArrayInputStream(
instance.getServerCaCert().getCert().getBytes(StandardCharsets.UTF_8)));
} catch (CertificateException e) {
throw
new RuntimeException(
String.format(
"Unable to parse certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
SSLContext sslContext = createSslContext(ephemeralCertificate, instanceCaCertificate);
return
new InstanceSslInfo(
instance.getIpAddresses().get(0).getIpAddress(),
ephemeralCertificate,
sslContext.getSocketFactory());
}
private SSLContext createSslContext(
Certificate ephemeralCertificate, Certificate instanceCaCertificate) {
KeyStore authKeyStore;
try {
authKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
authKeyStore.load(null, null);
KeyStore.PrivateKeyEntry pk =
new KeyStore.PrivateKeyEntry(
localKeyPair.getPrivate(), new Certificate[]{ephemeralCertificate});
authKeyStore.setEntry("ephemeral", pk, new PasswordProtection(new char[0]));
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("There was a problem initializing the auth key store", e);
}
KeyStore trustKeyStore;
try {
trustKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustKeyStore.load(null, null);
trustKeyStore.setCertificateEntry("instance", instanceCaCertificate);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("There was a problem initializing the trust key store", e);
}
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(authKeyStore, new char[0]);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X.509");
tmf.init(trustKeyStore);
sslContext.init(
keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return sslContext;
} catch (GeneralSecurityException e) {
throw new RuntimeException("There was a problem initializing the SSL context", e);
}
}
private DatabaseInstance obtainInstanceMetadata(
SQLAdmin adminApi, String instanceConnectionString, String projectId, String instanceName) {
DatabaseInstance instance;
try {
instance = adminApi.instances().get(projectId, instanceName).execute();
} catch (GoogleJsonResponseException e) {
if (e.getDetails() == null || e.getDetails().getErrors().isEmpty()) {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
String reason = e.getDetails().getErrors().get(0).getReason();
if (ADMIN_API_NOT_ENABLED_REASON.equals(reason)) {
String apiLink =
"https://console.cloud.google.com/apis/api/sqladmin/overview?project=" + projectId;
throw
new RuntimeException(
String.format(
"The Google Cloud SQL API is not enabled for project [%s]. Please "
+ "use the Google Developers Console to enable it: %s",
projectId,
apiLink));
} else if (INSTANCE_NOT_AUTHORIZED_REASON.equals(reason)) {
// TODO(berezv): check if this works on Compute Engine / App Engine
String who = "you are";
if (getCredentialServiceAccount(credential) != null) {
who = "[" + getCredentialServiceAccount(credential) + "] is";
}
throw
new RuntimeException(
String.format(
"Cloud SQL Instance [%s] does not exist or %s not authorized to "
+ "access it. Please check the instance and project names to make "
+ "sure they are correct.",
instanceConnectionString,
who));
} else {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
} catch (IOException e) {
throw
new RuntimeException(
String.format(
"Unable to retrieve information about Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
if (!instance.getBackendType().equals("SECOND_GEN")) {
throw
new IllegalArgumentException(
"This client only supports connections to Second Generation Cloud SQL "
+ "instances");
}
return instance;
}
private X509Certificate obtainEphemeralCertificate(
SQLAdmin adminApi, String instanceConnectionString, String projectId, String instanceName) {
StringBuilder publicKeyPemBuilder = new StringBuilder();
publicKeyPemBuilder.append("-----BEGIN RSA PUBLIC KEY-----\n");
publicKeyPemBuilder.append(
DatatypeConverter.printBase64Binary(localKeyPair.getPublic().getEncoded())
.replaceAll("(.{64})", "$1\n"));
publicKeyPemBuilder.append("\n");
publicKeyPemBuilder.append("-----END RSA PUBLIC KEY-----\n");
SslCertsCreateEphemeralRequest req = new SslCertsCreateEphemeralRequest();
req.setPublicKey(publicKeyPemBuilder.toString());
SslCert response;
try {
response = adminApi.sslCerts().createEphemeral(projectId, instanceName, req).execute();
} catch (GoogleJsonResponseException e) {
if (e.getDetails() == null || e.getDetails().getErrors().isEmpty()) {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
String reason = e.getDetails().getErrors().get(0).getReason();
if (INSTANCE_NOT_AUTHORIZED_REASON.equals(reason)) {
String who = "you have";
if (getCredentialServiceAccount(credential) != null) {
who = "[" + getCredentialServiceAccount(credential) + "] has";
}
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL Instance [%s]. "
+ "Make sure %s Editor or Owner role on the project.",
instanceConnectionString,
who));
} else {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
} catch (IOException e) {
throw
new RuntimeException(
String.format(
"Unable to obtain ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
try {
return
(X509Certificate) certificateFactory.generateCertificate(
new ByteArrayInputStream(response.getCert().getBytes(StandardCharsets.UTF_8)));
} catch (CertificateException e) {
throw
new RuntimeException(
String.format(
"Unable to parse ephemeral certificate for Cloud SQL instance [%s]",
instanceConnectionString),
e);
}
}
@Nullable
private String getCredentialServiceAccount(Credential credential) {
return
credential instanceof GoogleCredential
? ((GoogleCredential) credential).getServiceAccountId()
: null;
}
private static SQLAdmin createAdminApiClient(Credential credential) {
HttpTransport httpTransport;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("Unable to initialize HTTP transport", e);
}
String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY);
String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY);
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
SQLAdmin.Builder adminApiBuilder =
new Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Cloud SQL Java Socket Factory");
if (rootUrl != null) {
logTestPropertyWarning(API_ROOT_URL_PROPERTY);
adminApiBuilder.setRootUrl(rootUrl);
}
if (servicePath != null) {
logTestPropertyWarning(API_SERVICE_PATH_PROPERTY);
adminApiBuilder.setServicePath(servicePath);
}
return adminApiBuilder.build();
}
private static class ApplicationDefaultCredentialFactory implements CredentialFactory {
@Override
public Credential create() {
GoogleCredential credential;
try {
credential = GoogleCredential.getApplicationDefault();
} catch (IOException e) {
throw
new RuntimeException(
"Unable to obtain credentials to communicate with the Cloud SQL API", e);
}
if (credential.createScopedRequired()) {
credential = credential.createScoped(
Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN));
}
return credential;
}
}
private static KeyPair generateRsaKeyPair() {
KeyPairGenerator generator;
try {
generator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(
"Unable to initialize Cloud SQL socket factory because no RSA implementation is "
+ "available.");
}
generator.initialize(RSA_KEY_SIZE);
return generator.generateKeyPair();
}
private class InstanceLookupResult {
private final Optional<RuntimeException> exception;
private final long lastFailureMillis;
private final Optional<InstanceSslInfo> instanceSslInfo;
public InstanceLookupResult(RuntimeException exception) {
this.exception = Optional.of(exception);
this.lastFailureMillis = clock.now();
this.instanceSslInfo = Optional.absent();
}
public InstanceLookupResult(InstanceSslInfo instanceSslInfo) {
this.instanceSslInfo = Optional.of(instanceSslInfo);
this.exception = Optional.absent();
this.lastFailureMillis = 0;
}
public boolean isSuccessful() {
return !exception.isPresent();
}
public Optional<InstanceSslInfo> getInstanceSslInfo() {
return instanceSslInfo;
}
public Optional<RuntimeException> getException() {
return exception;
}
public long getLastFailureMillis() {
return lastFailureMillis;
}
}
private static class InstanceSslInfo {
private final String instanceIpAddress;
private final X509Certificate ephemeralCertificate;
private final SSLSocketFactory sslSocketFactory;
InstanceSslInfo(
String instanceIpAddress,
X509Certificate ephemeralCertificate,
SSLSocketFactory sslSocketFactory) {
this.instanceIpAddress = instanceIpAddress;
this.ephemeralCertificate = ephemeralCertificate;
this.sslSocketFactory = sslSocketFactory;
}
public String getInstanceIpAddress() {
return instanceIpAddress;
}
public X509Certificate getEphemeralCertificate() {
return ephemeralCertificate;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
}
@VisibleForTesting
enum CertificateCaching {
USE_CACHE,
BYPASS_CACHE
}
static class Clock {
long now() {
return System.currentTimeMillis();
}
}
}
| Fix invalid class reference in JavaDoc.
Replaced note about testing with a disclaimer about not using the class
directly.
| core/src/main/java/com/google/cloud/sql/mysql/SslSocketFactory.java | Fix invalid class reference in JavaDoc. | <ide><path>ore/src/main/java/com/google/cloud/sql/mysql/SslSocketFactory.java
<ide> * Factory responsible for obtaining an ephemeral certificate, if necessary, and establishing a
<ide> * secure connecting to a Cloud SQL instance.
<ide> *
<del> * <p>The implementation is separate from {@link SocketFactory} to make this code easier to test.
<add> * <p>This class should not be used directly, but only through the JDBC driver specific
<add> * {@code SocketFactory} implementations.
<add> *
<add> * <p>The API of this class is subject to change without notice.
<ide> */
<ide> public class SslSocketFactory {
<ide> private static final Logger logger = Logger.getLogger(SslSocketFactory.class.getName()); |
|
Java | apache-2.0 | 3fd56f87c57c87220d098e5e122df45c565e944e | 0 | FireBlade-Serv/FireFFA | package eu.fireblade.fireffa.items;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
public class Kits {
public static ArrayList<String> LoreCreator(String a, String b){
ArrayList<String> lore = new ArrayList<String>();
lore.add(a);
lore.add(b);
return lore;
}
public static ItemStack ItemGen(Material m, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
item.setItemMeta(itemM);
if(lore != null){
itemM.setLore(lore);
}
return item;
}
public static ItemStack ItemGen1(Material m, Enchantment ench, int level, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGen2(Material m, Enchantment ench, int level, Enchantment ench2, int level2, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
itemM.addEnchant(ench2, level2, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGen3(Material m, Enchantment ench, int level, Enchantment ench2, int level2, Enchantment ench3,
int level3, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
itemM.addEnchant(ench2, level2, true);
itemM.addEnchant(ench3, level3, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGenColorLeather(Material leatherPiece, String n, int nombre, int red, int green, int blue) {
ItemStack item = new ItemStack(leatherPiece);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setDisplayName(n);
meta.setColor(Color.fromBGR(blue, green, red));
meta.spigot().setUnbreakable(true);
item.setItemMeta(meta);
return item;
}
public static ItemStack ItemGen2ColorLeather(Material leatherPiece, Enchantment ench, int level ,String n, int nombre, int red, int green, int blue) {
ItemStack item = new ItemStack(leatherPiece);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setDisplayName(n);
meta.setColor(Color.fromBGR(blue, green, red));
meta.addEnchant(ench, level, true);
meta.spigot().setUnbreakable(true);
item.setItemMeta(meta);
return item;
}
public static ItemStack Bouf(Material m, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(ChatColor.BLUE+"Nourriture");
item.setItemMeta(itemM);
return item;
}
public static ItemStack generatePotItem(PotionType pt, int level, String name, boolean splash) {
Potion pot = new Potion(pt, level);
pot.setSplash(splash);
ItemStack potion = pot.toItemStack(1);
ItemMeta meta = potion.getItemMeta();
meta.setDisplayName(name);
potion.setItemMeta(meta);
return potion;
}
public static ItemStack generateMutiplePot(PotionEffectType pt, int level, int time, PotionEffectType pt2, int level2, int time2, String name, ArrayList<String> lore, int nombre) {
ItemStack Potion = new ItemStack(Material.POTION, 1);
PotionMeta PotionMeta = (PotionMeta) Potion.getItemMeta();
PotionMeta.setDisplayName(name);
PotionMeta.setLore(lore);
PotionMeta.addCustomEffect(new PotionEffect(pt, level, time), true);
PotionMeta.addCustomEffect(new PotionEffect(pt2, level2, time2), true);
Potion.setItemMeta(PotionMeta);
Potion po = new Potion((byte) 8258);
po.apply(Potion);
return Potion;
}
public static void kitDemolisseur(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_RED+"Chapeau du dmolisseur", 1, 89, 38, 38));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_RED+"Tunique du dmolisseur", 1, 89, 38, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_RED+"Pantalon du dmolisseur", 1, 89, 38, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_RED+"Bottes du dmolisseur", 1, 89, 38, 38));
p.getInventory().setItem(0, ItemGen2(Material.IRON_AXE, Enchantment.DAMAGE_ALL, 1, Enchantment.KNOCKBACK, 2, ChatColor.DARK_RED+"Hache de guerre", LoreCreator(ChatColor.BLUE+"Clique droit - Boule de feu", ChatColor.BLUE+"Consomme une boule de feu"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.getInventory().setItem(1, ItemGen(Material.FIREBALL, ChatColor.DARK_RED+"Boule de feu", null, 16));
}
public static void kitFantome(Player p) {
Clear(p);
p.getInventory().setItem(0, ItemGen(Material.WOOD_SWORD, ChatColor.GRAY+"pe du fantme", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.STICK, Enchantment.KNOCKBACK, 5, ChatColor.GRAY+"Bton du chtiment", null, 1));
p.getInventory().setItem(2, ItemGen(Material.BLAZE_ROD, ChatColor.GRAY+"Warp stick", LoreCreator(ChatColor.BLUE+"Clique droit -Tlporte", ChatColor.BLUE+"Utilisable toute les minutes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1));
}
public static void kitTank(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen1(Material.GOLD_HELMET, Enchantment.PROTECTION_ENVIRONMENTAL, 4, ChatColor.GOLD+"Casque du tank", null, 1));
p.getInventory().setChestplate(ItemGen1(Material.GOLD_CHESTPLATE, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Plastron du tank", null, 1));
p.getInventory().setLeggings(ItemGen1(Material.GOLD_LEGGINGS, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Jambires du tank", null, 1));
p.getInventory().setBoots(ItemGen1(Material.GOLD_BOOTS, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Bottes du tank", null, 1));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.KNOCKBACK, 4, ChatColor.GOLD+"pe du tank", null, 1));
p.getInventory().setItem(1, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GOLD+"Potion curative du tank", true));
p.getInventory().setItem(2, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GOLD+"Potion curative du tank", true));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitFlic (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_BLUE+"Chapeau du flic", 1, 76, 127, 153));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_BLUE+"Tunique du flic", 1, 51, 76, 178));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_BLUE+"Pantalon du flic", 1, 51, 76, 178));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_BLUE+"Bottes du flic", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.STICK, Enchantment.DAMAGE_ALL, 3, ChatColor.DARK_BLUE+"Matraque", null, 1));
p.getInventory().setItem(1, ItemGen(Material.FLINT_AND_STEEL, ChatColor.DARK_BLUE+"Flingue", LoreCreator(ChatColor.BLUE+"Clique droit - Boule de feu", ChatColor.BLUE+"Consomme une munition"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.getInventory().setItem(2, ItemGen(Material.FIREBALL, ChatColor.DARK_BLUE+"Munition", null, 12));
}
public static void kitMagicien (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen(Material.DIAMOND_HELMET, ChatColor.BLUE+"Casque du magicien", null, 1));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLUE+"Tunique du magicien", 1, 51, 76, 178));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.BLUE+"Pantalon du magicien", 1, 51, 76, 178));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLUE+"Bottes du magicien", 1, 153, 51, 51));
p.getInventory().setItem(0, ItemGen2(Material.STICK, Enchantment.KNOCKBACK, 3, Enchantment.DAMAGE_ALL, 2, ChatColor.BLUE+"Baguette magique", LoreCreator(ChatColor.BLUE+"Clique droit - Ralentit et aveugle", ChatColor.BLUE+"Consomme une poudre magique"), 1));
p.getInventory().setItem(1, ItemGen(Material.BLAZE_POWDER, ChatColor.BLUE+"Poudre magique", null, 3));
p.getInventory().setItem(2, generatePotItem(PotionType.REGEN, 2, ChatColor.BLUE+"Potion de rgneratrice du magicien", true));
p.getInventory().setItem(3, generatePotItem(PotionType.INSTANT_DAMAGE, 2, ChatColor.BLUE+"Potion dstructrice du magicien", true));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitChevalier (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GRAY+"Chapeau du chevalier", 1, 153, 153, 153));
p.getInventory().setChestplate(ItemGen(Material.CHAINMAIL_CHESTPLATE, ChatColor.GRAY+"Cotte de maille du chevalier", null, 1));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon du chevalier", 1, 153, 153, 153));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes du chevalier", 1, 153, 153, 153));
p.getInventory().setItem(0, ItemGen1(Material.STONE_SWORD, Enchantment.KNOCKBACK, 0-2, ChatColor.GRAY+"pe du Chevalier", null, 1));
p.getInventory().setItem(1, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GRAY+"Potion curative du chevalier", false));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitCactus (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen2ColorLeather(Material.LEATHER_HELMET, Enchantment.THORNS, 4, ChatColor.GREEN+"Chapeau du cactus", 1, 127, 204, 25));
p.getInventory().setChestplate(ItemGen2ColorLeather(Material.LEATHER_CHESTPLATE, Enchantment.THORNS, 4, ChatColor.GREEN+"Tunique du cactus", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGen2ColorLeather(Material.LEATHER_LEGGINGS, Enchantment.THORNS, 4, ChatColor.GREEN+"Pantalon du cactus", 1, 127, 204, 25));
p.getInventory().setBoots(ItemGen2ColorLeather(Material.LEATHER_BOOTS, Enchantment.THORNS, 4, ChatColor.GREEN+"Bottes du cactus", 1, 127, 204, 25));
p.getInventory().setItem(0, ItemGen1(Material.FLINT, Enchantment.DAMAGE_ALL, 1, ChatColor.GREEN+"pine", null,1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2));
}
public static void kitPiaf (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GRAY+"Chapeau du piaf", 1, 216, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GRAY+"Tunique du piaf", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon du piaf", 1, 153, 51, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes du piaf", 1, 229, 229, 51));
p.getInventory().setItem(0, ItemGen1(Material.SUGAR, Enchantment.DAMAGE_ALL, 4, ChatColor.GRAY+"Fiente", null, 1));
p.getInventory().setItem(1, ItemGen(Material.FEATHER, ChatColor.GRAY+"Vol", LoreCreator(ChatColor.BLUE+"Clique droit - Propulse en hauteur", ChatColor.BLUE+"Utilisable 25 fois"), 25));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitVoleurdame (Player p) {
Clear(p);
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 1);
ItemMeta skullM = skull.getItemMeta();
skullM.setDisplayName(ChatColor.BLACK+"Crne du voleur d'me");
skullM.addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, 2, true);
skull.setItemMeta(skullM);
p.getInventory().setHelmet(skull);
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLACK+"Tunique du voleur d'me", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGen(Material.CHAINMAIL_LEGGINGS, ChatColor.BLACK+"Jambire de maile du voleur d'me", null, 1));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLACK+"Bottes du voleur d'me", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen(Material.STONE_SWORD, ChatColor.BLACK+"pe du voleur d'me", LoreCreator(ChatColor.BLUE+"Clique droit - Vole 1,5 coeurs", ChatColor.BLUE+"45 secondes de rcupration"), 1));
p.getInventory().setItem(1, ItemGen(Material.REDSTONE, ChatColor.BLACK+"Puit de sang", LoreCreator(ChatColor.BLUE+"Clique droit - Utilise les mes accumules pour se rgnerer", ChatColor.BLUE+"Consomme le puit de sang (Exprience)"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitOITCman (Player p) {
Clear(p);
p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_DAMAGE, 999, ChatColor.RED+"OITC bow", LoreCreator(ChatColor.BLUE+"Les flches tuent l'impacte", ChatColor.BLUE+"Consomme une flche si la cible est rate"), 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"OITC arrow", null, 3));
p.getInventory().setItem(0, ItemGen(Material.STONE_SWORD, ChatColor.RED+"OITC sword", null, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitLapin (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.WHITE+"Chapeau du lapin", 1, 255, 255, 255));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.WHITE+"Tunique du lapin", 1, 255, 255, 255));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.WHITE+"Pantalon du lapin", 1, 255, 255, 255));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.WHITE+"Bottes du lapin", 1, 255, 255, 255));
p.getInventory().setItem(0, ItemGen1(Material.CARROT_ITEM, Enchantment.KNOCKBACK, 4, ChatColor.WHITE+"Carotte du lapin", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.GOLDEN_CARROT, Enchantment.DAMAGE_ALL, 4, ChatColor.WHITE+"Carotte magique du lapin", null, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 6));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitRusse(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau du russe", 1, 102, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GREEN+"Tunique du russe", 1, 63, 76, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GREEN+"Pantalon du russe", 1, 63, 76, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_GREEN+"Bottes du russe", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.DAMAGE_ALL, 2, ChatColor.DARK_GREEN+"pe de combat", null, 1));
p.getInventory().setItem(1, generateMutiplePot(PotionEffectType.INCREASE_DAMAGE, 2, 90, PotionEffectType.CONFUSION, 1, 90, ChatColor.DARK_GREEN+"Vodka", LoreCreator(ChatColor.BLUE+"Force II et naus II", ChatColor.BLUE+"1 minute"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitGrampa(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen(Material.GOLD_HELMET, ChatColor.DARK_GRAY+"Casque du grampa", null, 1));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GRAY+"Tunique du grampa", 1, 254, 254, 254));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GRAY+"Pantalon du grampa", 1, 229, 229, 51));
p.getInventory().setBoots(ItemGen(Material.LEATHER_BOOTS, ChatColor.DARK_GRAY+"Bottes du grampa", null, 1));
p.getInventory().setItem(0, ItemGen1(Material.INK_SACK, Enchantment.DAMAGE_ALL, 4, ChatColor.DARK_GRAY+"Dentier", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.STICK, Enchantment.KNOCKBACK, 10, ChatColor.DARK_GRAY+"Canne", null, 1));
p.getInventory().setItem(2, ItemGen(Material.INK_SACK, ChatColor.DARK_GRAY+"Pruneau", LoreCreator(ChatColor.BLUE+"Clique droit - Rgne 2 coeurs", ChatColor.BLUE+"Rcupration 1 minute 30"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitMineur(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.YELLOW+"Chapeau du mineur", 1, 229, 229, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.YELLOW+"Tunique du mineur", 1, 76, 127, 153));
p.getInventory().setLeggings(ItemGen(Material.LEATHER_LEGGINGS, ChatColor.YELLOW+"Pantalon du mineur", null, 1));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.YELLOW+"Bottes du mineur", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen2(Material.STONE_PICKAXE, Enchantment.DAMAGE_ALL, 2, Enchantment.KNOCKBACK, 1, ChatColor.YELLOW+"Pioche du mineur", null ,1));
p.getInventory().setItem(1, ItemGen1(Material.IRON_INGOT, Enchantment.DAMAGE_ALL, 3, ChatColor.YELLOW+"Lingot de la mort", null, 1));
p.getInventory().setItem(2, ItemGen2(Material.COAL, Enchantment.FIRE_ASPECT, 1, Enchantment.DAMAGE_ALL, 0-Integer.MAX_VALUE, ChatColor.YELLOW+"Charbon du mineur", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitJihadist (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_RED+"Chapeau du jihadist", 1, 213, 209, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_RED+"Tunique du jihadist", 1, 121, 104, 63));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_RED+"Pantalon du jihadist", 1, 121, 104, 63 ));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_RED+"Bottes du jihadist", 1, 216, 127, 51));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_FIRE, 1, ChatColor.DARK_RED+"Kalachnikov", null, 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.DARK_RED+"Munitions", null, 32));
p.getInventory().setItem(1, ItemGen(Material.REDSTONE, ChatColor.DARK_RED+"Allah akbar", LoreCreator(ChatColor.BLUE+"Clique droit - Se faire exploser", ChatColor.BLUE+"Vous tue instantanment"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitGamer (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GREEN+"Chapeau du gamer", 1, 127, 204, 25));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GREEN+"Tunique du gamer", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GREEN+"Pantalon du gamer", 1, 127, 204, 25 ));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GREEN+"Bottes du gamer", 1, 127, 204, 25));
p.getInventory().setItem(0, ItemGen2(Material.WOOD_SWORD, Enchantment.DAMAGE_ALL, 2, Enchantment.KNOCKBACK, 8, ChatColor.GREEN+"pe du hero", null, 1));
p.getInventory().setItem(1, ItemGen(Material.RED_MUSHROOM, ChatColor.GREEN+"Super champignon", LoreCreator(ChatColor.BLUE+"Clique droit - Force 2, 5 secondes", ChatColor.BLUE+"Rcupration 30 secondes"), 1));
p.getInventory().setItem(2, ItemGen(Material.RABBIT_FOOT, ChatColor.DARK_GREEN+"Super jump", LoreCreator(ChatColor.BLUE+"Clique droit - Saute une hauteur de 5 blocs", ChatColor.BLUE+"Rcupration 15 secondes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitSauvage (Player p) {
Clear(p);
p.getInventory().setLeggings(ItemGen2ColorLeather(Material.LEATHER_LEGGINGS, Enchantment.PROTECTION_ENVIRONMENTAL, 5, ChatColor.DARK_PURPLE+"Pantalon du sauvage", 1, 102, 127, 51));
p.getInventory().setItem(0, ItemGen1(Material.FISHING_ROD, Enchantment.DAMAGE_ALL, 4, ChatColor.DARK_PURPLE+"Massue", null, 1));
p.getInventory().setItem(1, ItemGen(Material.GRILLED_PORK, ChatColor.DARK_PURPLE+"Nourriture charnue", LoreCreator(ChatColor.BLUE+"Clique droit - Rgne 3 coeurs", ChatColor.BLUE+"1 utilisation"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArcherelementaire (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GREEN+"Chapeau de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GREEN+"Tunique de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GREEN+"Pantalon de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GREEN+"Bottes de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"OITC arrow", null, 32));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_KNOCKBACK, 5, ChatColor.GREEN+"Arc des adieux", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_FIRE, 1, ChatColor.GREEN+"Arc de feu", null, 1));
p.getInventory().setItem(2, ItemGen(Material.BOW, ChatColor.DARK_GREEN+"Arc de glace", LoreCreator(ChatColor.BLUE+"Ses flches ralentissent et aveugles", ChatColor.BLUE+"Pendant 2 secondes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitOcelot (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.YELLOW+"Chapeau de l'ocelot", 1, 229, 229, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.YELLOW+"Tunique de l'ocelot", 1, 229, 229, 51));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.YELLOW+"Pantalon de l'ocelot", 1, 229, 229, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.YELLOW+"Bottes de l'ocelot", 1, 229, 229, 51));
p.getInventory().setItem(0, ItemGen2(Material.RAW_FISH, Enchantment.DAMAGE_ALL, 3, Enchantment.KNOCKBACK, 6, ChatColor.YELLOW+"Coup de poisson", null, 1));
ItemStack bonemeal = new ItemStack(Material.INK_SACK, 1, (short)15);
ItemMeta bonemealM = bonemeal.getItemMeta();
bonemealM.setDisplayName(ChatColor.YELLOW+"Pelote de laine");
bonemealM.setLore(LoreCreator(ChatColor.BLUE+"Clique droit - Vitesse 2 pendant 5 secondes", ChatColor.BLUE+"Consomme 1 ficelle de pelote de laine, 10 secondes de rcupration"));
bonemeal.setItemMeta(bonemealM);
p.getInventory().setItem(1, bonemeal);
p.getInventory().setItem(2, ItemGen(Material.STRING, ChatColor.YELLOW+"Ficelle de pelote laine", null, 3));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArchervagabon (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GREEN+"Tunique de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GREEN+"Pantalon de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_GREEN+"Bottes de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_KNOCKBACK, 10, ChatColor.DARK_GREEN+"Arc de la mort", null, 1));
p.getInventory().setItem(1, ItemGen(Material.BOW, ChatColor.DARK_GREEN+"Arc de l'archer vagabon", null, 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"Flche de l'archer vagabon", null, 32));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArcherelite (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau de l'archer d'lite", 1, 114, 113, 57));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_INFINITE, 1, ChatColor.DARK_GREEN+"Arc mitrailleur", LoreCreator(ChatColor.BLUE+"N'a pas besoin d'tre charg", ChatColor.BLUE+"Pas de limite d'utilisation"), 1));
p.getInventory().setItem(1, ItemGen(Material.ARROW, ChatColor.RED+"Flche de l'archer vagabon", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitAssassin (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.BLACK+"Chapeau de l'assassin", 1, 25, 25, 25));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLACK+"Tunique de l'assassin", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.BLACK+"Pantalon de l'assassin", 1, 25, 25, 25));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLACK+"Bottes de l'assassin", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.KNOCKBACK, -10, ChatColor.BLACK+"Dague",null ,1));
p.getInventory().setItem(1, ItemGen1(Material.SHEARS, Enchantment.DAMAGE_ALL, 4, ChatColor.BLACK+"Couteau de l'gorgeur", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitPanda (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.WHITE+"Chapeau du panda", 1, 255, 255, 255));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.WHITE+"Tunique du panda", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.WHITE+"Pantalon du panda", 1, 255, 255, 255));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.WHITE+"Bottes du panda", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen2(Material.SUGAR_CANE, Enchantment.DAMAGE_ALL, 3, Enchantment.KNOCKBACK, 1, ChatColor.WHITE+"Bamboo", null, 1));
p.getInventory().setItem(1, ItemGen(Material.CLAY, ChatColor.WHITE+"Charge au sol", LoreCreator(ChatColor.BLUE+"Clique droit - Petite explosion", ChatColor.BLUE+"30 secondes de rcupration"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitInformaticien (Player p) {
Clear(p);
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GRAY+"Tunique de l'informaticien", 1, 102, 153, 216));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon de l'informaticien", 1, 25, 25, 25));
p.getInventory().setBoots(ItemGen(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes de l'informaticien", null, 1));
p.getInventory().setItem(0, ItemGen2(Material.CAULDRON_ITEM, Enchantment.DAMAGE_ALL, 4, Enchantment.KNOCKBACK, 1, ChatColor.GRAY+"Tour de pc", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.WOOD_HOE, Enchantment.KNOCKBACK, 5, ChatColor.GRAY+"Tournevis", null, 1));
p.getInventory().setItem(2, ItemGen1(Material.POWERED_RAIL, Enchantment.FIRE_ASPECT, 2, ChatColor.GRAY+"Carte graphique (AMD)", null, 1));
}
private static void Clear(Player p) {
p.getInventory().clear();
p.getInventory().setHelmet(null);
p.getInventory().setChestplate(null);
p.getInventory().setLeggings(null);
p.getInventory().setBoots(null);
for (PotionEffect effect : p.getActivePotionEffects()) {
p.removePotionEffect(effect.getType());
}
}
} | src/eu/fireblade/fireffa/items/Kits.java | package eu.fireblade.fireffa.items;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
public class Kits {
public static ArrayList<String> LoreCreator(String a, String b){
ArrayList<String> lore = new ArrayList<String>();
lore.add(a);
lore.add(b);
return lore;
}
public static ItemStack ItemGen(Material m, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
item.setItemMeta(itemM);
if(lore != null){
itemM.setLore(lore);
}
return item;
}
public static ItemStack ItemGen1(Material m, Enchantment ench, int level, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGen2(Material m, Enchantment ench, int level, Enchantment ench2, int level2, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
itemM.addEnchant(ench2, level2, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGen3(Material m, Enchantment ench, int level, Enchantment ench2, int level2, Enchantment ench3,
int level3, String n, ArrayList<String> lore, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(n);
itemM.spigot().setUnbreakable(true);
if(lore != null){
itemM.setLore(lore);
}
itemM.addEnchant(ench, level, true);
itemM.addEnchant(ench2, level2, true);
itemM.addEnchant(ench3, level3, true);
item.setItemMeta(itemM);
return item;
}
public static ItemStack ItemGenColorLeather(Material leatherPiece, String n, int nombre, int red, int green, int blue) {
ItemStack item = new ItemStack(leatherPiece);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setDisplayName(n);
meta.setColor(Color.fromBGR(blue, green, red));
meta.spigot().setUnbreakable(true);
item.setItemMeta(meta);
return item;
}
public static ItemStack ItemGen2ColorLeather(Material leatherPiece, Enchantment ench, int level ,String n, int nombre, int red, int green, int blue) {
ItemStack item = new ItemStack(leatherPiece);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setDisplayName(n);
meta.setColor(Color.fromBGR(blue, green, red));
meta.addEnchant(ench, level, true);
meta.spigot().setUnbreakable(true);
item.setItemMeta(meta);
return item;
}
public static ItemStack Bouf(Material m, int nombre) {
ItemStack item = new ItemStack(m, nombre);
ItemMeta itemM = item.getItemMeta();
itemM.setDisplayName(ChatColor.BLUE+"Nourriture");
item.setItemMeta(itemM);
return item;
}
public static ItemStack generatePotItem(PotionType pt, int level, String name, boolean splash) {
Potion pot = new Potion(pt, level);
pot.setSplash(splash);
ItemStack potion = pot.toItemStack(1);
ItemMeta meta = potion.getItemMeta();
meta.setDisplayName(name);
potion.setItemMeta(meta);
return potion;
}
public static ItemStack generateMutiplePot(PotionEffectType pt, int level, int time, PotionEffectType pt2, int level2, int time2, String name, ArrayList<String> lore, int nombre) {
ItemStack Potion = new ItemStack(Material.POTION, 1);
PotionMeta PotionMeta = (PotionMeta) Potion.getItemMeta();
PotionMeta.setDisplayName(name);
PotionMeta.setLore(lore);
PotionMeta.addCustomEffect(new PotionEffect(pt, level, time), true);
PotionMeta.addCustomEffect(new PotionEffect(pt2, level2, time2), true);
Potion.setItemMeta(PotionMeta);
Potion po = new Potion((byte) 8258);
po.apply(Potion);
return Potion;
}
public static void kitDemolisseur(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_RED+"Chapeau du dmolisseur", 1, 89, 38, 38));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_RED+"Tunique du dmolisseur", 1, 89, 38, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_RED+"Pantalon du dmolisseur", 1, 89, 38, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_RED+"Bottes du dmolisseur", 1, 89, 38, 38));
p.getInventory().setItem(0, ItemGen2(Material.IRON_AXE, Enchantment.DAMAGE_ALL, 1, Enchantment.KNOCKBACK, 2, ChatColor.DARK_RED+"Hache de guerre", LoreCreator(ChatColor.BLUE+"Clique droit - Boule de feu", ChatColor.BLUE+"Consomme une boule de feu"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.getInventory().setItem(1, ItemGen(Material.FIREBALL, ChatColor.DARK_RED+"Boule de feu", null, 16));
}
public static void kitFantome(Player p) {
Clear(p);
p.getInventory().setItem(0, ItemGen(Material.WOOD_SWORD, ChatColor.GRAY+"pe du fantme", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.STICK, Enchantment.KNOCKBACK, 5, ChatColor.GRAY+"Bton du chtiment", null, 1));
p.getInventory().setItem(2, ItemGen(Material.BLAZE_ROD, ChatColor.GRAY+"Warp stick", LoreCreator(ChatColor.BLUE+"Clique droit -Tlporte", ChatColor.BLUE+"Utilisable toute les minutes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1));
}
public static void kitTank(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen1(Material.GOLD_HELMET, Enchantment.PROTECTION_ENVIRONMENTAL, 4, ChatColor.GOLD+"Casque du tank", null, 1));
p.getInventory().setChestplate(ItemGen1(Material.GOLD_CHESTPLATE, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Plastron du tank", null, 1));
p.getInventory().setLeggings(ItemGen1(Material.GOLD_LEGGINGS, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Jambires du tank", null, 1));
p.getInventory().setBoots(ItemGen1(Material.GOLD_BOOTS, Enchantment.PROTECTION_FIRE, 4, ChatColor.GOLD+"Bottes du tank", null, 1));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.KNOCKBACK, 4, ChatColor.GOLD+"pe du tank", null, 1));
p.getInventory().setItem(1, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GOLD+"Potion curative du tank", true));
p.getInventory().setItem(2, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GOLD+"Potion curative du tank", true));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitFlic (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_BLUE+"Chapeau du flic", 1, 76, 127, 153));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_BLUE+"Tunique du flic", 1, 51, 76, 178));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_BLUE+"Pantalon du flic", 1, 51, 76, 178));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_BLUE+"Bottes du flic", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.STICK, Enchantment.DAMAGE_ALL, 3, ChatColor.DARK_BLUE+"Matraque", null, 1));
p.getInventory().setItem(1, ItemGen(Material.FLINT_AND_STEEL, ChatColor.DARK_BLUE+"Flingue", LoreCreator(ChatColor.BLUE+"Clique droit - Boule de feu", ChatColor.BLUE+"Consomme une munition"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.getInventory().setItem(2, ItemGen(Material.FIREBALL, ChatColor.DARK_BLUE+"Munition", null, 12));
}
public static void kitMagicien (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen(Material.DIAMOND_HELMET, ChatColor.BLUE+"Casque du magicien", null, 1));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLUE+"Tunique du magicien", 1, 51, 76, 178));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.BLUE+"Pantalon du magicien", 1, 51, 76, 178));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLUE+"Bottes du magicien", 1, 153, 51, 51));
p.getInventory().setItem(0, ItemGen2(Material.STICK, Enchantment.KNOCKBACK, 3, Enchantment.DAMAGE_ALL, 2, ChatColor.BLUE+"Baguette magique", LoreCreator(ChatColor.BLUE+"Clique droit - Ralentit et aveugle", ChatColor.BLUE+"Consomme une poudre magique"), 1));
p.getInventory().setItem(1, ItemGen(Material.BLAZE_POWDER, ChatColor.BLUE+"Poudre magique", null, 3));
p.getInventory().setItem(2, generatePotItem(PotionType.REGEN, 2, ChatColor.BLUE+"Potion de rgneratrice du magicien", true));
p.getInventory().setItem(3, generatePotItem(PotionType.INSTANT_DAMAGE, 2, ChatColor.BLUE+"Potion dstructrice du magicien", true));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitChevalier (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GRAY+"Chapeau du chevalier", 1, 153, 153, 153));
p.getInventory().setChestplate(ItemGen(Material.CHAINMAIL_CHESTPLATE, ChatColor.GRAY+"Cotte de maille du chevalier", null, 1));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon du chevalier", 1, 153, 153, 153));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes du chevalier", 1, 153, 153, 153));
p.getInventory().setItem(0, ItemGen1(Material.STONE_SWORD, Enchantment.KNOCKBACK, 0-2, ChatColor.GRAY+"pe du Chevalier", null, 1));
p.getInventory().setItem(1, generatePotItem(PotionType.INSTANT_HEAL, 2, ChatColor.GRAY+"Potion curative du chevalier", false));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitCactus (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen2ColorLeather(Material.LEATHER_HELMET, Enchantment.THORNS, 4, ChatColor.GREEN+"Chapeau du cactus", 1, 127, 204, 25));
p.getInventory().setChestplate(ItemGen2ColorLeather(Material.LEATHER_CHESTPLATE, Enchantment.THORNS, 4, ChatColor.GREEN+"Tunique du cactus", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGen2ColorLeather(Material.LEATHER_LEGGINGS, Enchantment.THORNS, 4, ChatColor.GREEN+"Pantalon du cactus", 1, 127, 204, 25));
p.getInventory().setBoots(ItemGen2ColorLeather(Material.LEATHER_BOOTS, Enchantment.THORNS, 4, ChatColor.GREEN+"Bottes du cactus", 1, 127, 204, 25));
p.getInventory().setItem(0, ItemGen1(Material.FLINT, Enchantment.DAMAGE_ALL, 1, ChatColor.GREEN+"pine", null,1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2));
}
public static void kitPiaf (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GRAY+"Chapeau du piaf", 1, 216, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GRAY+"Tunique du piaf", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon du piaf", 1, 153, 51, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes du piaf", 1, 229, 229, 51));
p.getInventory().setItem(0, ItemGen1(Material.SUGAR, Enchantment.DAMAGE_ALL, 4, ChatColor.GRAY+"Fiente", null, 1));
p.getInventory().setItem(1, ItemGen(Material.FEATHER, ChatColor.GRAY+"Vol", LoreCreator(ChatColor.BLUE+"Clique droit - Propulse en hauteur", ChatColor.BLUE+"Utilisable 25 fois"), 25));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitVoleurdame (Player p) {
Clear(p);
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 1);
ItemMeta skullM = skull.getItemMeta();
skullM.setDisplayName(ChatColor.BLACK+"Crne du voleur d'me");
skullM.addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, 2, true);
skull.setItemMeta(skullM);
p.getInventory().setHelmet(skull);
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLACK+"Tunique du voleur d'me", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGen(Material.CHAINMAIL_LEGGINGS, ChatColor.BLACK+"Jambire de maile du voleur d'me", null, 1));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLACK+"Bottes du voleur d'me", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen(Material.STONE_SWORD, ChatColor.BLACK+"pe du voleur d'me", LoreCreator(ChatColor.BLUE+"Clique droit - Vole 1,5 coeurs", ChatColor.BLUE+"45 secondes de rcupration"), 1));
p.getInventory().setItem(1, ItemGen(Material.REDSTONE, ChatColor.BLACK+"Puit de sang", LoreCreator(ChatColor.BLUE+"Clique droit - Utilise les mes accumules pour se rgnerer", ChatColor.BLUE+"Consomme le puit de sang (Exprience)"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitOITCman (Player p) {
Clear(p);
p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_DAMAGE, Integer.MAX_VALUE, ChatColor.RED+"OITC bow", LoreCreator(ChatColor.BLUE+"Les flches tuent l'impacte", ChatColor.BLUE+"Consomme une flche si la cible est rate"), 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"OITC arrow", null, 3));
p.getInventory().setItem(0, ItemGen(Material.STONE_SWORD, ChatColor.RED+"OITC sword", null, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitLapin (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.WHITE+"Chapeau du lapin", 1, 255, 255, 255));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.WHITE+"Tunique du lapin", 1, 255, 255, 255));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.WHITE+"Pantalon du lapin", 1, 255, 255, 255));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.WHITE+"Bottes du lapin", 1, 255, 255, 255));
p.getInventory().setItem(0, ItemGen1(Material.CARROT_ITEM, Enchantment.KNOCKBACK, 4, ChatColor.WHITE+"Carotte du lapin", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.GOLDEN_CARROT, Enchantment.DAMAGE_ALL, 4, ChatColor.WHITE+"Carotte magique du lapin", null, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 6));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitRusse(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau du russe", 1, 102, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GREEN+"Tunique du russe", 1, 63, 76, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GREEN+"Pantalon du russe", 1, 63, 76, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_GREEN+"Bottes du russe", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.DAMAGE_ALL, 2, ChatColor.DARK_GREEN+"pe de combat", null, 1));
p.getInventory().setItem(1, generateMutiplePot(PotionEffectType.INCREASE_DAMAGE, 2, 90, PotionEffectType.CONFUSION, 1, 90, ChatColor.DARK_GREEN+"Vodka", LoreCreator(ChatColor.BLUE+"Force II et naus II", ChatColor.BLUE+"1 minute"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitGrampa(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGen(Material.GOLD_HELMET, ChatColor.DARK_GRAY+"Casque du grampa", null, 1));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GRAY+"Tunique du grampa", 1, 254, 254, 254));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GRAY+"Pantalon du grampa", 1, 229, 229, 51));
p.getInventory().setBoots(ItemGen(Material.LEATHER_BOOTS, ChatColor.DARK_GRAY+"Bottes du grampa", null, 1));
p.getInventory().setItem(0, ItemGen1(Material.INK_SACK, Enchantment.DAMAGE_ALL, 4, ChatColor.DARK_GRAY+"Dentier", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.STICK, Enchantment.KNOCKBACK, 10, ChatColor.DARK_GRAY+"Canne", null, 1));
p.getInventory().setItem(2, ItemGen(Material.INK_SACK, ChatColor.DARK_GRAY+"Pruneau", LoreCreator(ChatColor.BLUE+"Clique droit - Rgne 2 coeurs", ChatColor.BLUE+"Rcupration 1 minute 30"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitMineur(Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.YELLOW+"Chapeau du mineur", 1, 229, 229, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.YELLOW+"Tunique du mineur", 1, 76, 127, 153));
p.getInventory().setLeggings(ItemGen(Material.LEATHER_LEGGINGS, ChatColor.YELLOW+"Pantalon du mineur", null, 1));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.YELLOW+"Bottes du mineur", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen2(Material.STONE_PICKAXE, Enchantment.DAMAGE_ALL, 2, Enchantment.KNOCKBACK, 1, ChatColor.YELLOW+"Pioche du mineur", null ,1));
p.getInventory().setItem(1, ItemGen1(Material.IRON_INGOT, Enchantment.DAMAGE_ALL, 3, ChatColor.YELLOW+"Lingot de la mort", null, 1));
p.getInventory().setItem(2, ItemGen2(Material.COAL, Enchantment.FIRE_ASPECT, 1, Enchantment.DAMAGE_ALL, 0-Integer.MAX_VALUE, ChatColor.YELLOW+"Charbon du mineur", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitJihadist (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_RED+"Chapeau du jihadist", 1, 213, 209, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_RED+"Tunique du jihadist", 1, 121, 104, 63));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_RED+"Pantalon du jihadist", 1, 121, 104, 63 ));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_RED+"Bottes du jihadist", 1, 216, 127, 51));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_FIRE, 1, ChatColor.DARK_RED+"Kalachnikov", null, 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.DARK_RED+"Munitions", null, 32));
p.getInventory().setItem(1, ItemGen(Material.REDSTONE, ChatColor.DARK_RED+"Allah akbar", LoreCreator(ChatColor.BLUE+"Clique droit - Se faire exploser", ChatColor.BLUE+"Vous tue instantanment"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitGamer (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GREEN+"Chapeau du gamer", 1, 127, 204, 25));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GREEN+"Tunique du gamer", 1, 127, 204, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GREEN+"Pantalon du gamer", 1, 127, 204, 25 ));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GREEN+"Bottes du gamer", 1, 127, 204, 25));
p.getInventory().setItem(0, ItemGen2(Material.WOOD_SWORD, Enchantment.DAMAGE_ALL, 2, Enchantment.KNOCKBACK, 8, ChatColor.GREEN+"pe du hero", null, 1));
p.getInventory().setItem(1, ItemGen(Material.RED_MUSHROOM, ChatColor.GREEN+"Super champignon", LoreCreator(ChatColor.BLUE+"Clique droit - Force 2, 5 secondes", ChatColor.BLUE+"Rcupration 30 secondes"), 1));
p.getInventory().setItem(2, ItemGen(Material.RABBIT_FOOT, ChatColor.DARK_GREEN+"Super jump", LoreCreator(ChatColor.BLUE+"Clique droit - Saute une hauteur de 5 blocs", ChatColor.BLUE+"Rcupration 15 secondes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitSauvage (Player p) {
Clear(p);
p.getInventory().setLeggings(ItemGen2ColorLeather(Material.LEATHER_LEGGINGS, Enchantment.PROTECTION_ENVIRONMENTAL, 5, ChatColor.DARK_PURPLE+"Pantalon du sauvage", 1, 102, 127, 51));
p.getInventory().setItem(0, ItemGen1(Material.FISHING_ROD, Enchantment.DAMAGE_ALL, 4, ChatColor.DARK_PURPLE+"Massue", null, 1));
p.getInventory().setItem(1, ItemGen(Material.GRILLED_PORK, ChatColor.DARK_PURPLE+"Nourriture charnue", LoreCreator(ChatColor.BLUE+"Clique droit - Rgne 3 coeurs", ChatColor.BLUE+"1 utilisation"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArcherelementaire (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.GREEN+"Chapeau de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GREEN+"Tunique de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GREEN+"Pantalon de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.GREEN+"Bottes de l'archer lmentaire", 1, 102, 127, 51));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"OITC arrow", null, 32));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_KNOCKBACK, 5, ChatColor.GREEN+"Arc des adieux", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_FIRE, 1, ChatColor.GREEN+"Arc de feu", null, 1));
p.getInventory().setItem(2, ItemGen(Material.BOW, ChatColor.DARK_GREEN+"Arc de glace", LoreCreator(ChatColor.BLUE+"Ses flches ralentissent et aveugles", ChatColor.BLUE+"Pendant 2 secondes"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitOcelot (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.YELLOW+"Chapeau de l'ocelot", 1, 229, 229, 51));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.YELLOW+"Tunique de l'ocelot", 1, 229, 229, 51));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.YELLOW+"Pantalon de l'ocelot", 1, 229, 229, 51));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.YELLOW+"Bottes de l'ocelot", 1, 229, 229, 51));
p.getInventory().setItem(0, ItemGen2(Material.RAW_FISH, Enchantment.DAMAGE_ALL, 3, Enchantment.KNOCKBACK, 6, ChatColor.YELLOW+"Coup de poisson", null, 1));
ItemStack bonemeal = new ItemStack(Material.INK_SACK, 1, (short)15);
ItemMeta bonemealM = bonemeal.getItemMeta();
bonemealM.setDisplayName(ChatColor.YELLOW+"Pelote de laine");
bonemealM.setLore(LoreCreator(ChatColor.BLUE+"Clique droit - Vitesse 2 pendant 5 secondes", ChatColor.BLUE+"Consomme 1 ficelle de pelote de laine, 10 secondes de rcupration"));
bonemeal.setItemMeta(bonemealM);
p.getInventory().setItem(1, bonemeal);
p.getInventory().setItem(2, ItemGen(Material.STRING, ChatColor.YELLOW+"Ficelle de pelote laine", null, 3));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArchervagabon (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.DARK_GREEN+"Tunique de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.DARK_GREEN+"Pantalon de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.DARK_GREEN+"Bottes de l'archer vagabon", 1, 63, 76, 38));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_KNOCKBACK, 10, ChatColor.DARK_GREEN+"Arc de la mort", null, 1));
p.getInventory().setItem(1, ItemGen(Material.BOW, ChatColor.DARK_GREEN+"Arc de l'archer vagabon", null, 1));
p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"Flche de l'archer vagabon", null, 32));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitArcherelite (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.DARK_GREEN+"Chapeau de l'archer d'lite", 1, 114, 113, 57));
p.getInventory().setItem(0, ItemGen1(Material.BOW, Enchantment.ARROW_INFINITE, 1, ChatColor.DARK_GREEN+"Arc mitrailleur", LoreCreator(ChatColor.BLUE+"N'a pas besoin d'tre charg", ChatColor.BLUE+"Pas de limite d'utilisation"), 1));
p.getInventory().setItem(1, ItemGen(Material.ARROW, ChatColor.RED+"Flche de l'archer vagabon", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitAssassin (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.BLACK+"Chapeau de l'assassin", 1, 25, 25, 25));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.BLACK+"Tunique de l'assassin", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.BLACK+"Pantalon de l'assassin", 1, 25, 25, 25));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.BLACK+"Bottes de l'assassin", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen1(Material.WOOD_SWORD, Enchantment.KNOCKBACK, -10, ChatColor.BLACK+"Dague",null ,1));
p.getInventory().setItem(1, ItemGen1(Material.SHEARS, Enchantment.DAMAGE_ALL, 4, ChatColor.BLACK+"Couteau de l'gorgeur", null, 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitPanda (Player p) {
Clear(p);
p.getInventory().setHelmet(ItemGenColorLeather(Material.LEATHER_HELMET, ChatColor.WHITE+"Chapeau du panda", 1, 255, 255, 255));
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.WHITE+"Tunique du panda", 1, 25, 25, 25));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.WHITE+"Pantalon du panda", 1, 255, 255, 255));
p.getInventory().setBoots(ItemGenColorLeather(Material.LEATHER_BOOTS, ChatColor.WHITE+"Bottes du panda", 1, 25, 25, 25));
p.getInventory().setItem(0, ItemGen2(Material.SUGAR_CANE, Enchantment.DAMAGE_ALL, 3, Enchantment.KNOCKBACK, 1, ChatColor.WHITE+"Bamboo", null, 1));
p.getInventory().setItem(1, ItemGen(Material.CLAY, ChatColor.WHITE+"Charge au sol", LoreCreator(ChatColor.BLUE+"Clique droit - Petite explosion", ChatColor.BLUE+"30 secondes de rcupration"), 1));
p.getInventory().setItem(8, Bouf(Material.CARROT_ITEM, 64));
}
public static void kitInformaticien (Player p) {
Clear(p);
p.getInventory().setChestplate(ItemGenColorLeather(Material.LEATHER_CHESTPLATE, ChatColor.GRAY+"Tunique de l'informaticien", 1, 102, 153, 216));
p.getInventory().setLeggings(ItemGenColorLeather(Material.LEATHER_LEGGINGS, ChatColor.GRAY+"Pantalon de l'informaticien", 1, 25, 25, 25));
p.getInventory().setBoots(ItemGen(Material.LEATHER_BOOTS, ChatColor.GRAY+"Bottes de l'informaticien", null, 1));
p.getInventory().setItem(0, ItemGen2(Material.CAULDRON_ITEM, Enchantment.DAMAGE_ALL, 4, Enchantment.KNOCKBACK, 1, ChatColor.GRAY+"Tour de pc", null, 1));
p.getInventory().setItem(1, ItemGen1(Material.WOOD_HOE, Enchantment.KNOCKBACK, 5, ChatColor.GRAY+"Tournevis", null, 1));
p.getInventory().setItem(2, ItemGen1(Material.POWERED_RAIL, Enchantment.FIRE_ASPECT, 2, ChatColor.GRAY+"Carte graphique (AMD)", null, 1));
}
private static void Clear(Player p) {
p.getInventory().clear();
p.getInventory().setHelmet(null);
p.getInventory().setChestplate(null);
p.getInventory().setLeggings(null);
p.getInventory().setBoots(null);
for (PotionEffect effect : p.getActivePotionEffects()) {
p.removePotionEffect(effect.getType());
}
}
} | kit OITCman | src/eu/fireblade/fireffa/items/Kits.java | kit OITCman | <ide><path>rc/eu/fireblade/fireffa/items/Kits.java
<ide> public static void kitOITCman (Player p) {
<ide> Clear(p);
<ide>
<del> p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_DAMAGE, Integer.MAX_VALUE, ChatColor.RED+"OITC bow", LoreCreator(ChatColor.BLUE+"Les flches tuent l'impacte", ChatColor.BLUE+"Consomme une flche si la cible est rate"), 1));
<add> p.getInventory().setItem(1, ItemGen1(Material.BOW, Enchantment.ARROW_DAMAGE, 999, ChatColor.RED+"OITC bow", LoreCreator(ChatColor.BLUE+"Les flches tuent l'impacte", ChatColor.BLUE+"Consomme une flche si la cible est rate"), 1));
<ide> p.getInventory().setItem(2, ItemGen(Material.ARROW, ChatColor.RED+"OITC arrow", null, 3));
<ide> p.getInventory().setItem(0, ItemGen(Material.STONE_SWORD, ChatColor.RED+"OITC sword", null, 1));
<ide> p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1)); |
|
JavaScript | mit | a7603cd09ccb0f5bdd2a048074ad85aff4ba2f8e | 0 | cappuccino/objjc | /*
* compiler.j
*
* Created by Martin Carlberg.
* Copyright 2013, Martin Carlberg.
*
* Additional work by Aparajita Fishman.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the MIT license (http://opensource.org/licenses/MIT).
*/
/* global define, acorn, window, CFURL, Executable, FileDependency, objj_getClass, objj_getProtocol, class_copyIvarList, class_copyProtocolList, class_copyMethodList, class_getSuperclass, method_getName, protocol_getName, protocol_copyMethodDescriptionList */
(function(mod)
{
"use strict";
// CommonJS
if (typeof exports === "object" && typeof module === "object")
return mod(
exports,
require("objj-acorn/acorn"),
require("objj-acorn/util/walk"),
require("source-map"));
// AMD
if (typeof define === "function" && define.amd)
return define(
[
"exports",
"objj-acorn/acorn",
"objj-acorn/util/walk",
"source-map"
], mod);
// Browser
mod(this.objjCompiler || (this.objjCompiler = {}), acorn, acorn.walk, null);
})
(function(exports, acorn, walk, sourceMap)
{
"use strict";
exports.version = "0.5.0";
exports.acorn = acorn;
var reservedIdentifiers = acorn.makePredicate("self _cmd undefined localStorage arguments"),
wordPrefixOperators = acorn.makePredicate("delete in instanceof new typeof void"),
isLogicalOrBinaryExpression = acorn.makePredicate("LogicalExpression BinaryExpression");
// The compiler first uses acorn to generate an AST. It then walks the AST to generate either
// a list of file dependencies or JavaScript code. File dependencies generation is only used
// by the Objective-J loader and runtime.
var CompilerGenerateFileDependencies = 1,
CompilerGenerateCode = 2;
// Options may be passed to further configure the compiler. These options are recognized:
var defaultOptions = {
// Acorn (parser) options. For more information see objj-acorn.
// We use a function here to create a new object every time we copy the default options.
acornOptions: function() { return Object.create(null); },
// If true, generates a source map for the compiled file.
sourceMap: false,
// What to generate.
generateWhat: CompilerGenerateCode,
// Pass in class definitions. New class definitions in the source file will be added to this when compiling.
classDefs: function() { return Object.create(null); },
// Pass in protocol definitions. New protocol definitions in the source file will be added to this when compiling.
protocolDefs: function() { return Object.create(null); },
// If true, the compiler generates source code from the AST. If false, the compiler copies source code
// from the source file.
// WARNING: The preprocessor does not work if this is false.
generate: true,
// If true, the compiler generates Objective-J code instead of JavaScript code. Of course this is really
// only useful if you want the compiler to reformat/beautify the code.
generateObjJ: false,
// The compiler uses JSON format objects which determine how the source code is formatted.
// Example formats are located in the formats directory.
format: null,
// The string to use to indent. Defaults to a single space.
indentString: " ",
// How many indentStrings to use when indenting generated code.
indentWidth: 4,
// If true, comments are included when generating code and the acorn options
// trackComments and trackCommentsIncludeLineBreak are set true.
includeComments: false,
// We support this here as the old Objective-J compiler (Not a real compiler, Preprocessor.js) transformed
// named function declarations to assignments.
// Example: 'function f(x) { return x }' transforms to: 'f = function(x) { return x }'
transformNamedFunctionToAssignment: false,
// Objective-J methods are implemented as functions. If this option is true, the functions
// are named $<class>_<method>, where <class> is the class name, and <method> is the method name.
// If this option is false, the function is anonymous.
generateMethodFunctionNames: true,
// If true, the compiler generates type information for method arguments.
generateMethodArgumentTypeSignatures: true,
// If true, the compiler generates type information for ivars.
generateIvarTypeSignatures: true,
};
function setupOptions(options)
{
options = options || Object.create(null);
for (var option in defaultOptions)
{
if (!options.hasOwnProperty(option))
{
var defaultOption = defaultOptions[option];
options[option] = typeof defaultOption === "function" ? defaultOption() : defaultOption;
}
}
return options;
}
var Scope = function(prev, base)
{
this.vars = Object.create(null);
if (base)
for (var key in base)
this[key] = base[key];
this.prev = prev;
if (prev)
{
this.compiler = prev.compiler;
this.nodeStack = prev.nodeStack.slice(0);
this.nodePriorStack = prev.nodePriorStack.slice(0);
this.nodeStackOverrideType = prev.nodeStackOverrideType.slice(0);
}
else
{
this.nodeStack = [];
this.nodePriorStack = [];
this.nodeStackOverrideType = [];
}
};
Scope.prototype.toString = function()
{
return this.ivars ? "ivars: " + JSON.stringify(this.ivars) : "<No ivars>";
};
Scope.prototype.compiler = function()
{
return this.compiler;
};
Scope.prototype.rootScope = function()
{
return this.prev ? this.prev.rootScope() : this;
};
Scope.prototype.isRootScope = function()
{
return !this.prev;
};
Scope.prototype.currentClassName = function()
{
return this.classDef ? this.classDef.name : (this.prev ? this.prev.currentClassName() : null);
};
Scope.prototype.currentProtocolName = function()
{
return this.protocolDef ? this.protocolDef.name : (this.prev ? this.prev.currentProtocolName() : null);
};
Scope.prototype.getIvarForCurrentClass = function(/* String */ ivarName)
{
if (this.ivars)
{
var ivar = this.ivars[ivarName];
if (ivar)
return ivar;
}
var prev = this.prev;
// Stop at the class declaration
if (prev && !this.classDef)
return prev.getIvarForCurrentClass(ivarName);
return null;
};
Scope.prototype.getLvar = function(/* String */ lvarName, /* BOOL */ stopAtMethod)
{
if (this.vars)
{
var lvar = this.vars[lvarName];
if (lvar)
return lvar;
}
var prev = this.prev;
// Stop at the method declaration
if (prev && (!stopAtMethod || !this.methodType))
return prev.getLvar(lvarName, stopAtMethod);
return null;
};
Scope.prototype.currentMethodType = function()
{
return this.methodType ? this.methodType : (this.prev ? this.prev.currentMethodType() : null);
};
Scope.prototype.copyAddedSelfToIvarsToParent = function()
{
if (this.prev && this.addedSelfToIvars) for (var key in this.addedSelfToIvars)
{
var addedSelfToIvar = this.addedSelfToIvars[key],
scopeAddedSelfToIvar = (this.prev.addedSelfToIvars || (this.prev.addedSelfToIvars = Object.create(null)))[key] || (this.prev.addedSelfToIvars[key] = []);
// Append at end in parent scope
scopeAddedSelfToIvar.push.apply(scopeAddedSelfToIvar, addedSelfToIvar);
}
};
Scope.prototype.addMaybeWarning = function(warning)
{
var rootScope = this.rootScope();
(rootScope._maybeWarnings || (rootScope._maybeWarnings = [])).push(warning);
};
Scope.prototype.maybeWarnings = function()
{
return this.rootScope()._maybeWarnings;
};
Scope.prototype.pushNode = function(node, overrideType)
{
/*
Here we push 3 things onto a stack. The node, override type and an array
that can keep track of prior nodes on this level. The current node is also
pushed to the last prior array.
Special-case when the node is the same as the parent node. This happens
when using an override type when walking the AST. The same prior list is
then used instead of a new empty one.
*/
var nodePriorStack = this.nodePriorStack,
length = nodePriorStack.length,
lastPriorList = length ? nodePriorStack[length - 1] : null,
lastNode = length ? this.nodeStack[length - 1] : null;
// First add this node to the parent list of nodes, if it has one.
// If not the same node push the node.
if (lastPriorList && lastNode !== node)
lastPriorList.push(node);
// Use the last prior list if it is the same node
nodePriorStack.push(lastNode === node ? lastPriorList : []);
this.nodeStack.push(node);
this.nodeStackOverrideType.push(overrideType);
};
Scope.prototype.popNode = function()
{
this.nodeStackOverrideType.pop();
this.nodePriorStack.pop();
return this.nodeStack.pop();
};
Scope.prototype.currentNode = function()
{
var nodeStack = this.nodeStack;
return nodeStack[nodeStack.length - 1];
};
Scope.prototype.currentOverrideType = function()
{
var nodeStackOverrideType = this.nodeStackOverrideType;
return nodeStackOverrideType[nodeStackOverrideType.length - 1];
};
Scope.prototype.priorNode = function()
{
var nodePriorStack = this.nodePriorStack,
length = nodePriorStack.length;
if (length > 1)
{
var parent = nodePriorStack[length - 2];
return parent[parent.length - 2] || null;
}
return null;
};
Scope.prototype.format = function(index, format, useOverrideForNode)
{
var nodeStack = this.nodeStack,
length = nodeStack.length;
index = index || 0;
if (index >= length)
return null;
// Get the nodes backwards from the stack
var i = length - index - 1,
currentNode = nodeStack[i],
currentFormat = format || this.compiler.format,
// Get the parent descriptions except if no format was provided, then it is the root description
parentFormats = format ? format.parent : currentFormat,
nextFormat;
if (parentFormats)
{
var nodeType = useOverrideForNode === currentNode ? this.nodeStackOverrideType[i] : currentNode.type;
nextFormat = parentFormats[nodeType];
if (useOverrideForNode === currentNode && !nextFormat)
return null;
}
if (nextFormat)
{
// Check for more 'parent' attributes or return nextFormat
return this.format(index + 1, nextFormat);
}
else
{
// Check for a virtual node one step up in the stack
nextFormat = this.format(index + 1, format, currentNode);
if (nextFormat)
return nextFormat;
else
{
// Ok, we have found a format description (currentFormat).
// Lets check if we have any other descriptions dependent on the prior node.
var priorFormats = currentFormat.prior;
if (priorFormats)
{
var priorNode = this.priorNode(),
priorFormat = priorFormats[priorNode ? priorNode.type : "None"];
if (priorFormat)
return priorFormat;
}
return currentFormat;
}
}
};
var GlobalVariableMaybeWarning = function(/* String */ aMessage, /* SpiderMonkey AST node */ node, /* String */ code)
{
this.message = createMessage(aMessage, node, code);
this.node = node;
};
GlobalVariableMaybeWarning.prototype.checkIfWarning = function(/* Scope */ scope)
{
var identifier = this.node.name;
return !scope.getLvar(identifier) &&
typeof global[identifier] === "undefined" &&
(typeof window === "undefined" || typeof window[identifier] === "undefined") &&
!scope.compiler.getClassDef(identifier);
};
function StringBuffer(useSourceNode, file)
{
if (useSourceNode)
{
this.rootNode = new sourceMap.SourceNode();
this.concat = this.concatSourceNode;
this.toString = this.toStringSourceNode;
this.isEmpty = this.isEmptySourceNode;
this.appendStringBuffer = this.appendStringBufferSourceNode;
this.length = this.lengthSourceNode;
this.file = file;
}
else
{
this.atoms = [];
this.concat = this.concatString;
this.toString = this.toStringString;
this.isEmpty = this.isEmptyString;
this.appendStringBuffer = this.appendStringBufferString;
this.length = this.lengthString;
}
}
StringBuffer.prototype.toStringString = function()
{
return this.atoms.join("");
};
StringBuffer.prototype.toStringSourceNode = function()
{
return this.rootNode.toStringWithSourceMap({file: this.file});
};
StringBuffer.prototype.concatString = function(aString)
{
this.atoms.push(aString);
};
StringBuffer.prototype.concatSourceNode = function(aString, node)
{
if (node)
{
//console.log("Snippet: " + aString + ", line: " + node.loc.start.line + ", column: " + node.loc.start.column + ", source: " + node.loc.source);
this.rootNode.add(new sourceMap.SourceNode(node.loc.start.line, node.loc.start.column, node.loc.source, aString));
}
else
this.rootNode.add(aString);
if (this.notEmpty)
this.notEmpty = true;
};
// '\n' will indent. '\n\<N>' will indent or dedent by <N> levels.
StringBuffer.prototype.concatFormat = function(aString)
{
if (!aString)
return;
var lines = aString.split("\n"),
size = lines.length;
if (size > 1)
{
this.concat(lines[0]);
for (var i = 1; i < size; i++)
{
var line = lines[i];
this.concat("\n");
if (line.slice(0, 1) === "\\")
{
var numberLength = 1,
indent = line.slice(1, 1 + numberLength);
if (indent === "-")
{
numberLength = 2;
indent = line.slice(1, 1 + numberLength);
}
var indentationNumber = parseInt(indent, 10);
if (indentationNumber)
{
this.concat(indentationNumber > 0 ?
indentation + new Array(indentationNumber * indentWidth + 1).join(indentString) :
indentation.substring(indentSize * -indentationNumber));
}
line = line.slice(1 + numberLength);
}
else if (line || i === size - 1)
{
// Ident if there is something between line breaks or the last linebreak
this.concat(indentation);
}
if (line)
this.concat(line);
}
}
else
this.concat(aString);
};
StringBuffer.prototype.isEmptyString = function()
{
return this.atoms.length !== 0;
};
StringBuffer.prototype.isEmptySourceNode = function()
{
return !this.notEmpty;
};
StringBuffer.prototype.appendStringBufferString = function(stringBuffer)
{
this.atoms.push.apply(this.atoms, stringBuffer.atoms);
};
StringBuffer.prototype.appendStringBufferSourceNode = function(stringBuffer)
{
this.rootNode.add(stringBuffer.rootNode);
};
StringBuffer.prototype.lengthString = function()
{
return this.atoms.length;
};
StringBuffer.prototype.lengthSourceNode = function()
{
return this.rootNode.children.length;
};
/*
Both ClassDef and ProtocolDef conform to a 'protocol' (that we can't declare in Javascript).
Both have the attribute 'protocols': Array of ProtocolDef that they conform to.
Both also have the functions: addInstanceMethod, addClassMethod, getInstanceMethod and getClassMethod
classDef = {
"className": aClassName,
"superClass": superClass ,
"ivars": myIvars,
"instanceMethods": instanceMethodDefs,
"classMethods": classMethodDefs,
"protocols": myProtocols
};
*/
var ClassDef = function(isImplementationDeclaration, name, superClass, ivars, instanceMethods, classMethods, protocols)
{
this.name = name;
if (superClass)
this.superClass = superClass;
if (ivars)
this.ivars = ivars;
if (isImplementationDeclaration)
{
this.instanceMethods = instanceMethods || Object.create(null);
this.classMethods = classMethods || Object.create(null);
}
if (protocols)
this.protocols = protocols;
};
ClassDef.prototype.addInstanceMethod = function(methodDef) {
this.instanceMethods[methodDef.name] = methodDef;
};
ClassDef.prototype.addClassMethod = function(methodDef) {
this.classMethods[methodDef.name] = methodDef;
};
ClassDef.prototype.listOfNotImplementedMethodsForProtocols = function(protocolDefs)
{
var resultList = [],
instanceMethods = this.getInstanceMethods(),
classMethods = this.getClassMethods();
for (var i = 0, size = protocolDefs.length; i < size; i++)
{
var protocolDef = protocolDefs[i],
protocolInstanceMethods = protocolDef.requiredInstanceMethods,
protocolClassMethods = protocolDef.requiredClassMethods,
inheritFromProtocols = protocolDef.protocols,
methodName,
methodDef;
if (protocolInstanceMethods)
{
for (methodName in protocolInstanceMethods)
{
methodDef = protocolInstanceMethods[methodName];
if (!instanceMethods[methodName])
resultList.push({"methodDef": methodDef, "protocolDef": protocolDef});
}
}
if (protocolClassMethods)
{
for (methodName in protocolClassMethods)
{
methodDef = protocolClassMethods[methodName];
if (!classMethods[methodName])
resultList.push({"methodDef": methodDef, "protocolDef": protocolDef});
}
}
if (inheritFromProtocols)
resultList = resultList.concat(this.listOfNotImplementedMethodsForProtocols(inheritFromProtocols));
}
return resultList;
};
ClassDef.prototype.getInstanceMethod = function(name)
{
var instanceMethods = this.instanceMethods;
if (instanceMethods)
{
var method = instanceMethods[name];
if (method)
return method;
}
var superClass = this.superClass;
if (superClass)
return superClass.getInstanceMethod(name);
return null;
};
ClassDef.prototype.getClassMethod = function(name)
{
var classMethods = this.classMethods;
if (classMethods)
{
var method = classMethods[name];
if (method)
return method;
}
var superClass = this.superClass;
if (superClass)
return superClass.getClassMethod(name);
return null;
};
// Return a new Array with all instance methods
ClassDef.prototype.getInstanceMethods = function()
{
var instanceMethods = this.instanceMethods;
if (instanceMethods)
{
var superClass = this.superClass,
returnObject = Object.create(null),
methodName;
if (superClass)
{
var superClassMethods = superClass.getInstanceMethods();
for (methodName in superClassMethods)
returnObject[methodName] = superClassMethods[methodName];
}
for (methodName in instanceMethods)
returnObject[methodName] = instanceMethods[methodName];
return returnObject;
}
return [];
};
// Return a new Array with all class methods
ClassDef.prototype.getClassMethods = function()
{
var classMethods = this.classMethods;
if (classMethods)
{
var superClass = this.superClass,
returnObject = Object.create(null),
methodName;
if (superClass)
{
var superClassMethods = superClass.getClassMethods();
for (methodName in superClassMethods)
returnObject[methodName] = superClassMethods[methodName];
}
for (methodName in classMethods)
returnObject[methodName] = classMethods[methodName];
return returnObject;
}
return [];
};
/*
protocolDef = {
"name": aProtocolName,
"protocols": inheritFromProtocols,
"requiredInstanceMethods": requiredInstanceMethodDefs,
"requiredClassMethods": requiredClassMethodDefs
};
*/
var ProtocolDef = function(name, protocols, requiredInstanceMethodDefs, requiredClassMethodDefs)
{
this.name = name;
this.protocols = protocols;
if (requiredInstanceMethodDefs)
this.requiredInstanceMethods = requiredInstanceMethodDefs;
if (requiredClassMethodDefs)
this.requiredClassMethods = requiredClassMethodDefs;
};
ProtocolDef.prototype.addInstanceMethod = function(methodDef)
{
(this.requiredInstanceMethods || (this.requiredInstanceMethods = Object.create(null)))[methodDef.name] = methodDef;
};
ProtocolDef.prototype.addClassMethod = function(methodDef)
{
(this.requiredClassMethods || (this.requiredClassMethods = Object.create(null)))[methodDef.name] = methodDef;
};
ProtocolDef.prototype.getInstanceMethod = function(name)
{
var instanceMethods = this.requiredInstanceMethods,
method;
if (instanceMethods)
{
method = instanceMethods[name];
if (method)
return method;
}
var protocols = this.protocols;
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i];
method = protocol.getInstanceMethod(name);
if (method)
return method;
}
return null;
};
ProtocolDef.prototype.getClassMethod = function(name)
{
var classMethods = this.requiredClassMethods,
method;
if (classMethods)
{
method = classMethods[name];
if (method)
return method;
}
var protocols = this.protocols;
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i];
method = protocol.getInstanceMethod(name);
if (method)
return method;
}
return null;
};
// methodDef = {"types": types, "name": selector}
var MethodDef = function(name, types)
{
this.name = name;
this.types = types;
};
var Compiler = function(/*String*/ source, /*String*/ url, options)
{
this.source = source;
this.URL = typeof CFURL !== "undefined" ? new CFURL(url) : url;
this.options = options = setupOptions(options);
this.generateWhat = options.generateWhat;
this.classDefs = options.classDefs;
this.protocolDefs = options.protocolDefs;
this.generate = options.generate;
this.createSourceMap = options.sourceMap;
this.format = options.format;
this.includeComments = options.includeComments;
this.transformNamedFunctionToAssignment = options.transformNamedFunctionToAssignment;
this.jsBuffer = new StringBuffer(this.createSourceMap, url);
this.imBuffer = null;
this.cmBuffer = null;
this.dependencies = [];
this.warnings = [];
this.lastPos = 0;
var acornOptions = options.acornOptions;
if (!acornOptions.sourceFile)
acornOptions.sourceFile = this.URL;
if (options.sourceMap && !acornOptions.locations)
acornOptions.locations = true;
// We never want (line:column) in the error messages
acornOptions.lineNoInErrorMessage = false;
try
{
this.AST = acorn.parse(this.source, options.acornOptions);
}
catch (e)
{
if (e.lineStart)
{
var message = this.prettifyMessage(e, "ERROR");
console.log(message);
}
throw e;
}
var compiler = compile,
generator;
if (this.generateWhat === CompilerGenerateCode)
{
generator = codeGenerator;
if (options.includeComments || options.format)
compiler = compileWithFormat;
}
else
generator = dependencyCollector;
compiler(this.AST, new Scope(null, {compiler: this}), generator);
if (this.createSourceMap)
{
var s = this.jsBuffer.toString();
this.compiledCode = s.code;
this.sourceMap = s.map;
}
else
{
this.compiledCode = this.jsBuffer.toString();
}
};
Compiler.importStack = [];
exports.compileToExecutable = function(/*String*/ source, /*CFURL*/ url, options)
{
Compiler.currentCompileFile = url;
return new Compiler(source, url, options).executable();
};
exports.compileToIMBuffer = function(/*String*/ source, /*CFURL*/ url, classDefs, protocolDefs)
{
var options = { classDefs: classDefs, protocolDefs: protocolDefs };
return new Compiler(source, url, options).IMBuffer();
};
exports.compile = function(/*String*/ source, /*CFURL*/ url, options)
{
return new Compiler(source, url, options);
};
exports.compileFileDependencies = function(/*String*/ source, /*CFURL*/ url, options)
{
Compiler.currentCompileFile = url;
(options || (options = {})).generateWhat = CompilerGenerateFileDependencies;
return new Compiler(source, url, options).executable();
};
Compiler.prototype.addWarning = function(/* Warning */ aWarning)
{
this.warnings.push(aWarning);
};
Compiler.prototype.getIvarForClass = function(/* String */ ivarName, /* Scope */ scope)
{
var ivar = scope.getIvarForCurrentClass(ivarName);
if (ivar)
return ivar;
var c = this.getClassDef(scope.currentClassName());
while (c)
{
var ivars = c.ivars;
if (ivars)
{
var ivarDef = ivars[ivarName];
if (ivarDef)
return ivarDef;
}
c = c.superClass;
}
};
Compiler.prototype.getClassDef = function(/* String */ aClassName)
{
if (!aClassName)
return null;
var c = this.classDefs[aClassName];
if (c)
return c;
if (typeof objj_getClass === "function")
{
var aClass = objj_getClass(aClassName);
if (aClass)
{
var ivars = class_copyIvarList(aClass),
ivarSize = ivars.length,
myIvars = Object.create(null),
protocols = class_copyProtocolList(aClass),
protocolSize = protocols.length,
myProtocols = Object.create(null),
instanceMethodDefs = Compiler.methodDefsFromMethodList(class_copyMethodList(aClass)),
classMethodDefs = Compiler.methodDefsFromMethodList(class_copyMethodList(aClass.isa)),
superClass = class_getSuperclass(aClass);
for (var i = 0; i < ivarSize; i++)
{
var ivar = ivars[i];
myIvars[ivar.name] = {"type": ivar.type, "name": ivar.name};
}
for (i = 0; i < protocolSize; i++)
{
var protocol = protocols[i],
protocolName = protocol_getName(protocol),
protocolDef = this.getProtocolDef(protocolName);
myProtocols[protocolName] = protocolDef;
}
c = new ClassDef(true, aClassName, superClass ? this.getClassDef(superClass.name) : null,
myIvars, instanceMethodDefs, classMethodDefs, myProtocols);
this.classDefs[aClassName] = c;
return c;
}
}
return null;
};
Compiler.prototype.getProtocolDef = function(/* String */ aProtocolName)
{
if (!aProtocolName)
return null;
var p = this.protocolDefs[aProtocolName];
if (p)
return p;
if (typeof objj_getProtocol === "function")
{
var aProtocol = objj_getProtocol(aProtocolName);
if (aProtocol)
{
var protocolName = protocol_getName(aProtocol),
requiredInstanceMethods = protocol_copyMethodDescriptionList(aProtocol, true, true),
requiredInstanceMethodDefs = Compiler.methodDefsFromMethodList(requiredInstanceMethods),
requiredClassMethods = protocol_copyMethodDescriptionList(aProtocol, true, false),
requiredClassMethodDefs = Compiler.methodDefsFromMethodList(requiredClassMethods),
protocols = aProtocol.protocols,
inheritFromProtocols = [];
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
inheritFromProtocols.push(this.getProtocolDef(protocols[i].name));
}
p = new ProtocolDef(protocolName, inheritFromProtocols, requiredInstanceMethodDefs, requiredClassMethodDefs);
this.protocolDefs[aProtocolName] = p;
return p;
}
}
return null;
};
Compiler.methodDefsFromMethodList = function(/* Array */ methodList)
{
var methodSize = methodList.length,
myMethods = Object.create(null);
for (var i = 0; i < methodSize; i++)
{
var method = methodList[i],
methodName = method_getName(method);
myMethods[methodName] = new MethodDef(methodName, method.types);
}
return myMethods;
};
// FIXME: Does not work any more
Compiler.prototype.executable = function()
{
if (!this._executable)
this._executable = new Executable(this.jsBuffer ? this.jsBuffer.toString() : null,
this.dependencies, this.URL, null, this);
return this._executable;
};
Compiler.prototype.IMBuffer = function()
{
return this.imBuffer;
};
Compiler.prototype.code = function()
{
return this.compiledCode;
};
Compiler.prototype.ast = function()
{
return JSON.stringify(this.AST, null, indentWidth);
};
Compiler.prototype.map = function()
{
return JSON.stringify(this.sourceMap);
};
Compiler.prototype.prettifyMessage = function(/* Message */ aMessage, /* String */ messageType)
{
var line = this.source.substring(aMessage.lineStart, aMessage.lineEnd),
message = "\n" + line;
message += (new Array(aMessage.column + 1)).join(" ");
message += (new Array(Math.min(1, line.length) + 1)).join("^") + "\n";
message += messageType + " line " + aMessage.line + " in " + this.URL + ": " + aMessage.message;
return message;
};
Compiler.prototype.syntaxError = function(message, node)
{
var pos = acorn.getLineInfo(this.source, node.start),
error = {
message: message,
line: pos.line,
column: pos.column,
lineStart: pos.lineStart,
lineEnd: pos.lineEnd
};
return new SyntaxError(this.prettifyMessage(error, "ERROR"));
};
Compiler.prototype.pushImport = function(url)
{
// This is used to keep track of imports. Each time the compiler imports a file the url is pushed here.
Compiler.importStack.push(url);
};
Compiler.prototype.popImport = function()
{
Compiler.importStack.pop();
};
function createMessage(/* String */ aMessage, /* SpiderMonkey AST node */ node, /* String */ code)
{
var message = acorn.getLineInfo(code, node.start);
message.message = aMessage;
return message;
}
function compile(node, state, visitor)
{
function compileNode(node, state, override)
{
visitor[override || node.type](node, state, compileNode);
}
compileNode(node, state);
}
function compileWithFormat(node, state, visitor)
{
var lastNode, lastComment;
function compileNode(node, state, override)
{
var compiler = state.compiler,
includeComments = compiler.includeComments,
localLastNode = lastNode,
sameNode = localLastNode === node,
i;
lastNode = node;
if (includeComments && !sameNode && node.commentsBefore && node.commentsBefore !== lastComment)
{
for (i = 0; i < node.commentsBefore.length; i++)
compiler.jsBuffer.concat(node.commentsBefore[i]);
}
state.pushNode(node, override);
var format = state.format();
//console.log("format: " + JSON.stringify(format) + ", node.type: " + node.type + ", override: " + override);
if (!sameNode && format && format.before)
compiler.jsBuffer.concatFormat(format.before);
visitor[override || node.type](node, state, compileNode, format);
if (!sameNode && format && format.after)
compiler.jsBuffer.concatFormat(format.after);
state.popNode();
if (includeComments && !sameNode && node.commentsAfter)
{
for (i = 0; i < node.commentsAfter.length; i++)
compiler.jsBuffer.concat(node.commentsAfter[i]);
lastComment = node.commentsAfter;
}
else
lastComment = null;
}
compileNode(node, state);
}
function isIdempotentExpression(node)
{
/* jshint -W004 */
switch (node.type)
{
case "Literal":
case "Identifier":
return true;
case "ArrayExpression":
for (var i = 0; i < node.elements.length; i++)
{
if (!isIdempotentExpression(node.elements[i]))
return false;
}
return true;
case "DictionaryLiteral":
for (var i = 0; i < node.keys.length; i++)
{
if (!isIdempotentExpression(node.keys[i]))
return false;
if (!isIdempotentExpression(node.values[i]))
return false;
}
return true;
case "ObjectExpression":
for (var i = 0; i < node.properties.length; i++)
if (!isIdempotentExpression(node.properties[i].value))
return false;
return true;
case "FunctionExpression":
for (var i = 0; i < node.params.length; i++)
if (!isIdempotentExpression(node.params[i]))
return false;
return true;
case "SequenceExpression":
for (var i = 0; i < node.expressions.length; i++)
if (!isIdempotentExpression(node.expressions[i]))
return false;
return true;
case "UnaryExpression":
return isIdempotentExpression(node.argument);
case "BinaryExpression":
return isIdempotentExpression(node.left) && isIdempotentExpression(node.right);
case "ConditionalExpression":
return isIdempotentExpression(node.test) && isIdempotentExpression(node.consequent) && isIdempotentExpression(node.alternate);
case "MemberExpression":
return isIdempotentExpression(node.object) && (!node.computed || isIdempotentExpression(node.property));
case "Dereference":
return isIdempotentExpression(node.expr);
case "Reference":
return isIdempotentExpression(node.element);
default:
return false;
}
}
// We do not allow dereferencing of expressions with side effects because
// we might need to evaluate the expression twice in certain uses of deref,
// which is not obvious when you look at the deref operator in plain code.
function checkCanDereference(state, node)
{
if (!isIdempotentExpression(node))
throw state.compiler.syntaxError("Dereference of expression with side effects", node);
}
function parenthesize(compileNode)
{
return function(node, state, override, format)
{
state.compiler.jsBuffer.concat("(");
compileNode(node, state, override, format);
state.compiler.jsBuffer.concat(")");
};
}
function parenthesizeExpression(generate, node, subnode, state, compileNode, right)
{
(generate && subnodeHasPrecedence(node, subnode, right) ? parenthesize(compileNode) : compileNode)(subnode, state, "Expression");
}
function getAccessorInfo(accessors, ivarName)
{
var property = (accessors.property && accessors.property.name) || ivarName,
getter = (accessors.getter && accessors.getter.name) || property;
return { property: property, getter: getter };
}
var operatorPrecedence = {
// MemberExpression
// These two are never used, since the "computed" attribute of the MemberExpression
// determines which one to use.
// ".": 0, "[]": 0,
// NewExpression
// This is never used.
// "new": 1,
// All these are UnaryExpression or UpdateExpression and are never used.
//"!": 2, "~": 2, "-": 2, "+": 2, "++": 2, "--": 2, "typeof": 2, "void": 2, "delete": 2,
// BinaryExpression
"*": 3, "/": 3, "%": 3,
"+": 4, "-": 4,
"<<": 5, ">>": 5, ">>>": 5,
"<": 6, "<=": 6, ">": 6, ">=": 6, "in": 6, "instanceof": 6,
"==": 7, "!=": 7, "===": 7, "!==": 7,
"&": 8,
"^": 9,
"|": 10,
// LogicalExpression
"&&": 11,
"||": 12
// ConditionalExpression
// AssignmentExpression
};
var expressionTypePrecedence = {
MemberExpression: 0,
CallExpression: 1,
NewExpression: 2,
FunctionExpression: 3,
UnaryExpression: 4, UpdateExpression: 4,
BinaryExpression: 5,
LogicalExpression: 6,
ConditionalExpression: 7,
AssignmentExpression: 8
};
// Returns true if subnode has higher precedence than node.
// If subnode is the right subnode of a binary expression, right is true.
function subnodeHasPrecedence(node, subnode, right)
{
var nodeType = node.type,
nodePrecedence = expressionTypePrecedence[nodeType] || -1,
subnodePrecedence = expressionTypePrecedence[subnode.type] || -1,
nodeOperatorPrecedence,
subnodeOperatorPrecedence;
return subnodePrecedence > nodePrecedence ||
(nodePrecedence === subnodePrecedence && isLogicalOrBinaryExpression(nodeType) &&
((subnodeOperatorPrecedence = operatorPrecedence[subnode.operator]) > (nodeOperatorPrecedence = operatorPrecedence[node.operator]) ||
(right === true && nodeOperatorPrecedence === subnodeOperatorPrecedence)
)
);
}
var indentString = defaultOptions.indentString,
indentWidth = defaultOptions.indentWidth,
indentSize = indentWidth * indentString.length,
indentStep = new Array(indentWidth + 1).join(indentString),
indentation = "";
// Helper for codeGenerator.ClassDeclarationStatement
function declareClass(compiler, node, classDef, className, isInterfaceDeclaration, generateObjJ, saveJSBuffer) // -> classDef
{
if (node.superclassname)
{
// To be an @implementation declaration it must have method and ivar dictionaries.
// If there are neither, it's a @class declaration. If there is no ivar dictionary,
// it's an @interface declaration.
// TODO: Create a ClassDef object and add this logic to it
if (classDef && classDef.ivars)
// It has a real implementation declaration already
throw compiler.syntaxError("Duplicate class " + className, node.classname);
if (isInterfaceDeclaration && classDef && classDef.instanceMethods && classDef.classMethods)
// It has a interface declaration already
throw compiler.syntaxError("Duplicate interface definition for class " + className, node.classname);
var superClassDef = compiler.getClassDef(node.superclassname.name);
if (!superClassDef)
{
var errorMessage = "Can't find superclass " + node.superclassname.name;
for (var i = Compiler.importStack.length; --i >= 0;)
errorMessage += "\n" + new Array((Compiler.importStack.length - i) * 2 + 1).join(" ") + "Imported by: " + Compiler.importStack[i];
throw compiler.syntaxError(errorMessage, node.superclassname);
}
classDef = new ClassDef(!isInterfaceDeclaration, className, superClassDef, Object.create(null));
if (!generateObjJ)
saveJSBuffer.concat("{var the_class = objj_allocateClassPair(" + node.superclassname.name + ", \"" + className + "\"),\nmeta_class = the_class.isa;", node);
}
else if (node.categoryname)
{
classDef = compiler.getClassDef(className);
if (!classDef)
throw compiler.syntaxError("Class " + className + " not found ", node.classname);
if (!generateObjJ)
{
saveJSBuffer.concat("{\nvar the_class = objj_getClass(\"" + className + "\")\n", node);
saveJSBuffer.concat("if (!the_class) throw new SyntaxError(\"*** Could not find definition for class \\\"" + className + "\\\"\");\n");
saveJSBuffer.concat("var meta_class = the_class.isa;");
}
}
else
{
classDef = new ClassDef(!isInterfaceDeclaration, className, null, Object.create(null));
if (!generateObjJ)
saveJSBuffer.concat("{var the_class = objj_allocateClassPair(Nil, \"" + className + "\"),\nmeta_class = the_class.isa;", node);
}
return classDef;
}
// Helper for codeGenerator.ClassDeclarationStatement
function addIvars(compiler, node, compileNode, state, classDef, className, classScope, firstIvarDeclaration, generateObjJ, saveJSBuffer) // -> hasAccessors
{
var hasAccessors = false;
if (generateObjJ)
{
saveJSBuffer.concat("{");
indentation += indentStep;
}
for (var i = 0; i < node.ivardeclarations.length; i++)
{
var ivarDecl = node.ivardeclarations[i],
ivarType = ivarDecl.ivartype ? ivarDecl.ivartype.name : null,
ivarIdentifier = ivarDecl.id,
ivarName = ivarIdentifier.name,
ivars = classDef.ivars,
ivar = {"type": ivarType, "name": ivarName},
accessors = ivarDecl.accessors;
if (ivars[ivarName])
throw compiler.syntaxError("Instance variable '" + ivarName + "'is already declared for class " + className, ivarIdentifier);
if (generateObjJ)
compileNode(ivarDecl, state, "IvarDeclaration");
else
{
if (firstIvarDeclaration)
{
firstIvarDeclaration = false;
saveJSBuffer.concat("class_addIvars(the_class, [");
}
else
saveJSBuffer.concat(", ");
if (compiler.options.generateIvarTypeSignatures)
saveJSBuffer.concat("new objj_ivar(\"" + ivarName + "\", \"" + ivarType + "\")", node);
else
saveJSBuffer.concat("new objj_ivar(\"" + ivarName + "\")", node);
}
if (ivarDecl.outlet)
ivar.outlet = true;
ivars[ivarName] = ivar;
if (!classScope.ivars)
classScope.ivars = Object.create(null);
classScope.ivars[ivarName] = {type: "ivar", name: ivarName, node: ivarIdentifier, ivar: ivar};
if (accessors)
{
var info = getAccessorInfo(accessors, ivarName),
property = info.property,
getterName = info.getter;
classDef.addInstanceMethod(new MethodDef(getterName, [ivarType]));
if (!accessors.readonly)
{
var setterName = accessors.setter ? accessors.setter.name : null;
if (!setterName)
{
var start = property.charAt(0) === "_" ? 1 : 0;
setterName = (start ? "_" : "") + "set" + property.substr(start, 1).toUpperCase() + property.substring(start + 1) + ":";
}
classDef.addInstanceMethod(new MethodDef(setterName, ["void", ivarType]));
}
hasAccessors = true;
}
}
return hasAccessors;
}
// Helper for codeGenerator.ClassDeclarationStatement
function generateGetterSetter(compiler, node)
{
var getterSetterBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
// Add the class declaration to compile accessors correctly
getterSetterBuffer.concat(compiler.source.substring(node.start, node.endOfIvars));
getterSetterBuffer.concat("\n");
for (var i = 0; i < node.ivardeclarations.length; i++)
{
var ivarDecl = node.ivardeclarations[i],
ivarType = ivarDecl.ivartype ? ivarDecl.ivartype.name : null,
ivarName = ivarDecl.id.name,
accessors = ivarDecl.accessors;
if (!accessors)
continue;
var info = getAccessorInfo(accessors, ivarName),
property = info.property,
getterName = info.getter,
getterCode = "- (" + (ivarType ? ivarType : "id") + ")" + getterName + "\n{\nreturn " + ivarName + ";\n}\n";
getterSetterBuffer.concat(getterCode);
if (accessors.readonly)
continue;
var setterName = accessors.setter ? accessors.setter.name : null;
if (!setterName)
{
var start = property.charAt(0) === "_" ? 1 : 0;
setterName = (start ? "_" : "") + "set" + property.substr(start, 1).toUpperCase() + property.substring(start + 1) + ":";
}
var setterCode = "- (void)" + setterName + "(" + (ivarType ? ivarType : "id") + ")newValue\n{\n";
if (accessors.copy)
setterCode += "if (" + ivarName + " !== newValue)\n" + ivarName + " = [newValue copy];\n}\n";
else
setterCode += ivarName + " = newValue;\n}\n";
getterSetterBuffer.concat(setterCode);
}
getterSetterBuffer.concat("\n@end");
// Remove all @accessors or we will get an infinite loop
var source = getterSetterBuffer.toString().replace(/@accessors(\(.*\))?/g, ""),
imBuffer = exports.compileToIMBuffer(source, "Accessors", compiler.classDefs, compiler.protocolDefs);
// Add the accessor methods first to the instance method buffer.
// This will allow manually added set and get methods to override the compiler generated methods.
compiler.imBuffer.concat(imBuffer);
}
function checkProtocolConformance(compiler, node, classDef, protocols)
{
// Lookup the protocolDefs for the protocols
var protocolDefs = [];
for (var i = 0, size = protocols.length; i < size; i++)
protocolDefs.push(compiler.getProtocolDef(protocols[i].name));
var unimplementedMethods = classDef.listOfNotImplementedMethodsForProtocols(protocolDefs);
if (unimplementedMethods && unimplementedMethods.length > 0)
{
for (i = 0, size = unimplementedMethods.length; i < size; i++)
{
var unimplementedMethod = unimplementedMethods[i],
methodDef = unimplementedMethod.methodDef,
protocolDef = unimplementedMethod.protocolDef;
compiler.addWarning(createMessage("Method '" + methodDef.name + "' in protocol '" + protocolDef.name + "' is not implemented", node.classname, compiler.source));
}
}
}
var dependencyCollector = walk.make(
{
ImportStatement: function(node, state)
{
var urlString = node.filename.value;
if (typeof FileDependency !== "undefined")
state.compiler.dependencies.push(new FileDependency(new CFURL(urlString), node.isLocal));
else
state.compiler.dependencies.push(urlString);
}
});
var codeGenerator = walk.make({
Program: function(node, state, compileNode)
{
var compiler = state.compiler;
indentString = compiler.options.indentString;
indentWidth = compiler.options.indentWidth;
indentSize = indentWidth * indentString.length;
indentStep = new Array(indentWidth + 1).join(indentString);
indentation = "";
for (var i = 0; i < node.body.length; i++)
compileNode(node.body[i], state, "Statement");
if (!compiler.generate)
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.end));
// Check for warnings
var maybeWarnings = state.maybeWarnings();
if (maybeWarnings)
{
for (i = 0; i < maybeWarnings.length; i++)
{
var maybeWarning = maybeWarnings[i];
if (maybeWarning.checkIfWarning(state))
compiler.addWarning(maybeWarning.message);
}
}
},
BlockStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
skipIndentation = state.skipIndentation,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("{");
buffer.concatFormat(format.afterLeftBrace);
}
else
{
if (skipIndentation)
delete state.skipIndentation;
else
buffer.concat(indentation.substring(indentSize));
buffer.concat("{\n");
}
}
for (var i = 0; i < node.body.length; i++)
compileNode(node.body[i], state, "Statement");
if (compiler.generate)
{
if (format)
{
buffer.concatFormat(format.beforeRightBrace);
buffer.concat("}");
}
else
{
buffer.concat(indentation.substring(indentSize));
buffer.concat("}");
if (!skipIndentation && state.isDecl !== false)
buffer.concat("\n");
state.indentBlockLevel--;
}
}
},
ExpressionStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate && !format;
if (generate)
compiler.jsBuffer.concat(indentation);
compileNode(node.expression, state, "Expression");
if (generate)
compiler.jsBuffer.concat(";\n");
},
IfStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("if", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
// Keep the 'else' and 'if' on the same line if it is an 'else if'
if (!state.superNodeIsElse)
buffer.concat(indentation);
else
delete state.superNodeIsElse;
buffer.concat("if (", node);
}
}
compileNode(node.test, state, "Expression");
if (compiler.generate)
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
var expressionClose = node.consequent.type === "EmptyStatement" ? ");" : ")";
if (format)
{
buffer.concat(expressionClose);
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(expressionClose + "\n");
}
indentation += indentStep;
compileNode(node.consequent, state, "Statement");
indentation = indentation.substring(indentSize);
var alternate = node.alternate;
if (alternate)
{
var alternateNotIf = alternate.type !== "IfStatement";
if (compiler.generate)
{
var emptyStatement = alternate.type === "EmptyStatement",
elseClause = emptyStatement ? "else;" : "else";
if (format)
{
buffer.concatFormat(format.beforeElse); // Do we need this?
buffer.concat(elseClause);
buffer.concatFormat(format.afterElse);
}
else
{
buffer.concat(indentation + elseClause);
buffer.concat(alternateNotIf ? "\n" : " ");
}
}
if (alternateNotIf)
indentation += indentStep;
else
state.superNodeIsElse = true;
compileNode(alternate, state, "Statement");
if (alternateNotIf)
indentation = indentation.substring(indentSize);
}
},
LabeledStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
compileNode(node.label, state, "IdentifierName");
if (format)
{
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(": ");
}
compileNode(node.body, state, "Statement");
},
BreakStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var label = node.label,
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
if (label)
{
if (format)
{
buffer.concat("break", node);
buffer.concatFormat(format.beforeLabel);
}
else
buffer.concat("break ", node);
compileNode(label, state, "IdentifierName");
if (!format)
buffer.concat(";\n");
}
else
buffer.concat(format ? "break" : "break;\n", node);
}
},
ContinueStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var label = node.label,
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
if (label)
{
if (format)
{
buffer.concat("continue", node);
buffer.concatFormat(format.beforeLabel);
}
else
buffer.concat("continue ", node);
compileNode(label, state, "IdentifierName");
if (!format)
buffer.concat(";\n");
}
else
buffer.concat(format ? "continue" : "continue;\n", node);
}
},
WithStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("with", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("with(", node);
}
}
compileNode(node.object, state, "Expression");
if (compiler.generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(")\n");
}
indentation += indentStep;
compileNode(node.body, state, "Statement");
indentation = indentation.substring(indentSize);
},
SwitchStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("switch", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(", node);
}
else
{
buffer.concat(indentation);
buffer.concat("switch (", node);
}
}
compileNode(node.discriminant, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
buffer.concat("{");
buffer.concatFormat(format.afterLeftBrace);
}
else
buffer.concat(") {\n");
}
indentation += indentStep;
for (var i = 0; i < node.cases.length; i++)
{
var cs = node.cases[i];
if (cs.test)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCase);
buffer.concat("case", node);
buffer.concatFormat(format.afterCase);
}
else
{
buffer.concat(indentation);
buffer.concat("case ");
}
}
compileNode(cs.test, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(":\n");
}
}
else if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCase);
buffer.concat("default");
buffer.concatFormat(format.afterCase);
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat("default:\n");
}
indentation += indentStep;
for (var j = 0; j < cs.consequent.length; j++)
compileNode(cs.consequent[j], state, "Statement");
indentation = indentation.substring(indentSize);
}
indentation = indentation.substring(indentSize);
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeRightBrace);
buffer.concat("}");
}
else
{
buffer.concat(indentation);
buffer.concat("}\n");
}
}
},
ReturnStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
buffer.concat("return", node);
}
if (node.argument)
{
if (generate)
buffer.concatFormat(format ? format.beforeExpression : " ");
compileNode(node.argument, state, "Expression");
}
if (generate && !format)
buffer.concat(";\n");
},
ThrowStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
buffer.concat("throw", node);
buffer.concatFormat(format ? format.beforeExpression : " ");
}
compileNode(node.argument, state, "Expression");
if (generate && !format)
buffer.concat(";\n");
},
TryStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format) buffer.concat(indentation);
buffer.concat("try", node);
buffer.concatFormat(format ? format.beforeStatement : " ");
}
indentation += indentStep;
if (!format)
state.skipIndentation = true;
compileNode(node.block, state, "Statement");
indentation = indentation.substring(indentSize);
if (node.handler)
{
var handler = node.handler,
inner = new Scope(state),
param = handler.param,
name = param.name;
inner.vars[name] = {type: "catch clause", node: param};
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCatch);
buffer.concat("catch");
buffer.concatFormat(format.afterCatch);
buffer.concat("(");
compileNode(param, state, "IdentifierName");
buffer.concat(")");
buffer.concatFormat(format.beforeCatchStatement);
}
else
{
buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("catch(");
buffer.concat(name);
buffer.concat(") ");
}
}
indentation += indentStep;
inner.skipIndentation = true;
compileNode(handler.body, inner, "ScopeBody");
indentation = indentation.substring(indentSize);
inner.copyAddedSelfToIvarsToParent();
}
if (node.finalizer)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCatch);
buffer.concat("finally");
buffer.concatFormat(format.beforeCatchStatement);
}
else
{
buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("finally ");
}
}
indentation += indentStep;
state.skipIndentation = true;
compileNode(node.finalizer, state, "Statement");
indentation = indentation.substring(indentSize);
}
if (generate && !format)
buffer.concat("\n");
},
WhileStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("while", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("while (", node);
}
}
compileNode(node.test, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
DoWhileStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("do", node);
buffer.concatFormat(format.beforeStatement);
}
else
{
buffer.concat(indentation);
buffer.concat("do\n", node);
}
}
indentation += indentStep;
compileNode(node.body, state, "Statement");
indentation = indentation.substring(indentSize);
if (generate)
{
if (format)
{
buffer.concat("while");
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("while (");
}
}
compileNode(node.test, state, "Expression");
if (generate)
buffer.concatFormat(format ? ")" : ");\n");
},
ForStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("for", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("for (", node);
}
}
if (node.init)
compileNode(node.init, state, "ForInit");
if (generate)
buffer.concat(format ? ";" : "; ");
if (node.test)
compileNode(node.test, state, "Expression");
if (generate)
buffer.concat(format ? ";" : "; ");
if (node.update)
compileNode(node.update, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
ForInStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("for", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("for (", node);
}
}
compileNode(node.left, state, "ForInit");
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeIn);
buffer.concat("in");
buffer.concatFormat(format.afterIn);
}
else
buffer.concat(" in ");
}
compileNode(node.right, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
ForInit: function(node, state, compileNode)
{
if (node.type === "VariableDeclaration")
{
state.isFor = true;
compileNode(node, state);
delete state.isFor;
}
else
compileNode(node, state, "Expression");
},
DebuggerStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var buffer = compiler.jsBuffer;
if (format)
buffer.concat("debugger", node);
else
{
buffer.concat(indentation);
buffer.concat("debugger;\n", node);
}
}
},
Function: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
inner = new Scope(state),
decl = node.type === "FunctionDeclaration",
id = node.id;
inner.isDecl = decl;
for (var i = 0; i < node.params.length; i++)
inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]};
if (generate && !format)
buffer.concat(indentation);
if (id)
{
var name = id.name;
(decl ? state : inner).vars[name] = {type: decl ? "function" : "function name", node: id};
if (compiler.transformNamedFunctionToAssignment)
{
if (generate)
{
buffer.concat(name);
buffer.concat(" = ");
}
else
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(name);
buffer.concat(" = function");
compiler.lastPos = id.end;
}
}
}
if (generate)
{
buffer.concat("function", node);
if (!compiler.transformNamedFunctionToAssignment && id)
{
if (!format)
buffer.concat(" ");
compileNode(id, state, "IdentifierName");
}
if (format)
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
for (i = 0; i < node.params.length; i++)
{
if (i)
buffer.concat(format ? "," : ", ");
compileNode(node.params[i], state, "IdentifierName");
}
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(")\n");
}
indentation += indentStep;
compileNode(node.body, inner, "ScopeBody");
indentation = indentation.substring(indentSize);
inner.copyAddedSelfToIvarsToParent();
},
VariableDeclaration: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer,
decl,
identifier;
if (generate)
{
buffer = compiler.jsBuffer;
if (!state.isFor && !format)
buffer.concat(indentation);
buffer.concat(format ? "var" : "var ", node);
}
for (var i = 0; i < node.declarations.length; i++)
{
decl = node.declarations[i];
identifier = decl.id.name;
if (i)
{
if (generate)
{
if (format)
buffer.concat(",");
else
{
if (state.isFor)
buffer.concat(", ");
else
{
buffer.concat(",\n");
buffer.concat(indentation);
buffer.concat(" ");
}
}
}
}
state.vars[identifier] = {type: "var", node: decl.id};
compileNode(decl.id, state, "IdentifierName");
if (decl.init)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeEqual);
buffer.concat("=");
buffer.concatFormat(format.afterEqual);
}
else
buffer.concat(" = ");
}
compileNode(decl.init, state, "Expression");
}
// FIXME: Extract to function
// Here we check back if a ivar with the same name exists and if we have prefixed 'self.' on previous uses.
// If this is the case we have to remove the prefixes and issue a warning that the variable hides the ivar.
if (state.addedSelfToIvars)
{
var addedSelfToIvar = state.addedSelfToIvars[identifier];
if (addedSelfToIvar)
{
var atoms = state.compiler.jsBuffer.atoms,
size = addedSelfToIvar.length;
for (i = 0; i < size; i++)
{
var dict = addedSelfToIvar[i];
atoms[dict.index] = "";
compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides instance variable", dict.node, compiler.source));
}
state.addedSelfToIvars[identifier] = [];
}
}
}
if (generate && !format && !state.isFor)
buffer.concat(";\n"); // Don't add ';' if this is a for statement but do it if this is a statement
},
ThisExpression: function(node, state)
{
var compiler = state.compiler;
if (compiler.generate)
compiler.jsBuffer.concat("this", node);
},
ArrayExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("[", node);
}
for (var i = 0; i < node.elements.length; i++)
{
var elt = node.elements[i];
if (generate && i !== 0)
{
if (format)
{
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
}
else
buffer.concat(", ");
}
if (elt)
compileNode(elt, state, "Expression");
}
if (generate)
buffer.concat("]");
},
ObjectExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
properties = node.properties,
buffer = compiler.jsBuffer;
if (generate)
buffer.concat("{", node);
for (var i = 0, size = properties.length; i < size; i++)
{
var prop = properties[i];
if (generate)
{
if (i)
{
if (format)
{
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
}
else
buffer.concat(", ");
}
state.isPropertyKey = true;
compileNode(prop.key, state, "Expression");
delete state.isPropertyKey;
if (format)
{
buffer.concatFormat(format.beforeColon);
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(": ");
}
else if (prop.key.raw && prop.key.raw.charAt(0) === "@")
{
buffer.concat(compiler.source.substring(compiler.lastPos, prop.key.start));
compiler.lastPos = prop.key.start + 1;
}
compileNode(prop.value, state, "Expression");
}
if (generate)
buffer.concat("}");
},
SequenceExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("(");
}
for (var i = 0; i < node.expressions.length; i++)
{
if (generate && i !== 0)
{
if (format)
{
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
}
else
buffer.concat(", ");
}
compileNode(node.expressions[i], state, "Expression");
}
if (generate)
buffer.concat(")");
},
UnaryExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
argument = node.argument;
if (generate)
{
var buffer = compiler.jsBuffer;
if (node.prefix)
{
buffer.concat(node.operator, node);
if (wordPrefixOperators(node.operator))
buffer.concat(" ");
parenthesizeExpression(generate, node, argument, state, compileNode);
}
else
{
parenthesizeExpression(generate, node, argument, state, compileNode);
buffer.concat(node.operator);
}
}
else
compileNode(argument, state, "Expression");
},
UpdateExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer;
if (node.argument.type === "Dereference")
{
checkCanDereference(state, node.argument);
// @deref(x)++ and ++@deref(x) require special handling.
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Output the dereference function, "(...)(z)"
buffer.concat((node.prefix ? "" : "(") + "(");
// The thing being dereferenced.
if (!generate)
compiler.lastPos = node.argument.expr.start;
compileNode(node.argument.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.argument.expr.end));
buffer.concat(")(");
if (!generate)
compiler.lastPos = node.argument.start;
compileNode(node.argument, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.argument.end));
buffer.concat(" " + node.operator.substring(0, 1) + " 1)" + (node.prefix ? "" : (node.operator === "++" ? " - 1)" : " + 1)")));
if (!generate)
compiler.lastPos = node.end;
return;
}
if (node.prefix)
{
if (generate)
{
buffer.concat(node.operator, node);
if (wordPrefixOperators(node.operator))
buffer.concat(" ");
}
parenthesizeExpression(generate, node, node.argument, state, compileNode);
}
else
{
parenthesizeExpression(generate, node, node.argument, state, compileNode);
if (generate)
buffer.concat(node.operator);
}
},
BinaryExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
var buffer = compiler.jsBuffer;
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
},
LogicalExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
var buffer = compiler.jsBuffer;
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
},
AssignmentExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer;
if (node.left.type === "Dereference")
{
checkCanDereference(state, node.left);
// @deref(x) = z -> x(z) etc
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Output the dereference function, "(...)(z)"
buffer.concat("(");
// What's being dereferenced could itself be an expression, such as when dereferencing a deref.
if (!generate)
compiler.lastPos = node.left.expr.start;
compileNode(node.left.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.left.expr.end));
buffer.concat(")(");
// Now "(x)(...)". We have to manually expand +=, -=, *= etc.
if (node.operator !== "=")
{
// Output the whole .left, not just .left.expr.
if (!generate)
compiler.lastPos = node.left.start;
compileNode(node.left, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.left.end));
buffer.concat(" " + node.operator.substring(0, 1) + " ");
}
if (!generate)
compiler.lastPos = node.right.start;
compileNode(node.right, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.right.end));
buffer.concat(")");
if (!generate)
compiler.lastPos = node.end;
}
else
{
var saveAssignment = state.assignment;
state.assignment = true;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
state.assignment = saveAssignment;
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
if (state.isRootScope() && node.left.type === "Identifier" && !state.getLvar(node.left.name))
state.vars[node.left.name] = {type: "global", node: node.left};
}
},
ConditionalExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
parenthesizeExpression(generate, node, node.test, state, compileNode);
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concatFormat(format.beforeOperator);
buffer.concat("?");
buffer.concatFormat(format.afterOperator);
}
else
buffer.concat(" ? ");
}
compileNode(node.consequent, state, "Expression");
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeOperator);
buffer.concat(":");
buffer.concatFormat(format.afterOperator);
}
else
buffer.concat(" : ");
}
compileNode(node.alternate, state, "Expression");
},
NewExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
nodeArguments = node.arguments,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("new ", node);
}
parenthesizeExpression(generate, node, node.callee, state, compileNode);
if (generate)
buffer.concat("(");
if (nodeArguments)
{
for (var i = 0, size = nodeArguments.length; i < size; i++)
{
if (i > 0 && generate)
buffer.concatFormat(format ? "," : ", ");
compileNode(nodeArguments[i], state, "Expression");
}
}
if (generate)
buffer.concat(")");
},
CallExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
nodeArguments = node.arguments,
generate = compiler.generate,
buffer;
parenthesizeExpression(generate, node, node.callee, state, compileNode);
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("(");
}
if (nodeArguments)
{
for (var i = 0, size = nodeArguments.length; i < size; i++)
{
if (i > 0 && generate)
buffer.concat(format ? "," : ", ");
compileNode(nodeArguments[i], state, "Expression");
}
}
if (generate)
buffer.concat(")");
},
MemberExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
computed = node.computed;
parenthesizeExpression(generate, node, node.object, state, compileNode);
if (generate)
compiler.jsBuffer.concat(computed ? "[" : ".", node);
state.secondMemberExpression = !computed;
// No parentheses when it is computed, '[' amd ']' are the same thing.
parenthesizeExpression(generate && !computed, node, node.property, state, compileNode);
state.secondMemberExpression = false;
if (generate && computed)
compiler.jsBuffer.concat("]");
},
Identifier: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate,
identifier = node.name;
if (state.currentMethodType() === "-" && !state.secondMemberExpression && !state.isPropertyKey)
{
var lvar = state.getLvar(identifier, true), // Only look inside method
ivar = compiler.getIvarForClass(identifier, state);
if (ivar)
{
if (lvar)
compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides instance variable", node, compiler.source));
else
{
var nodeStart = node.start;
if (!generate)
{
do
{
// The Spider Monkey AST tree includes any parentheses in start and end properties
// so we have to make sure we skip those
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, nodeStart));
compiler.lastPos = nodeStart;
}
while (compiler.source.substr(nodeStart++, 1) === "(");
}
// Save the index of where the "self." string is stored and the node.
// These will be used if we find a variable declaration that is hoisting this identifier.
((state.addedSelfToIvars || (state.addedSelfToIvars = Object.create(null)))[identifier] || (state.addedSelfToIvars[identifier] = [])).push({node: node, index: compiler.jsBuffer.length()});
compiler.jsBuffer.concat("self.", node);
}
}
// Don't check for warnings if it is a reserved word like self, localStorage, _cmd, etc...
else if (!reservedIdentifiers(identifier))
{
var message,
classOrGlobal = typeof global[identifier] !== "undefined" || (typeof window !== "undefined" && typeof window[identifier] !== "undefined") || compiler.getClassDef(identifier),
globalVar = state.getLvar(identifier);
// It can't be declared with a @class statement
if (classOrGlobal && (!globalVar || globalVar.type !== "class"))
{
/* jshint -W035 */
/* Turned off this warning as there are many many warnings when compiling the Cappuccino frameworks - Martin
if (lvar) {
message = compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides global variable", node, compiler.source));
}*/
}
else if (!globalVar)
{
if (state.assignment)
{
message = new GlobalVariableMaybeWarning("Creating global variable inside function or method '" + identifier + "'", node, compiler.source);
// Turn off these warnings for this identifier, we only want one.
state.vars[identifier] = {type: "remove global warning", node: node};
}
else
{
message = new GlobalVariableMaybeWarning("Using unknown class or uninitialized global variable '" + identifier + "'", node, compiler.source);
}
}
if (message)
state.addMaybeWarning(message);
}
}
if (generate)
compiler.jsBuffer.concat(identifier, node);
},
// Use this when there should not be a look up to issue warnings or add 'self.' before ivars
IdentifierName: function(node, state)
{
var compiler = state.compiler;
if (compiler.generate)
compiler.jsBuffer.concat(node.name, node);
},
Literal: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate;
if (generate)
{
if (node.raw && node.raw.charAt(0) === "@")
compiler.jsBuffer.concat(node.raw.substring(1), node);
else
compiler.jsBuffer.concat(node.raw, node);
}
else if (node.raw.charAt(0) === "@")
{
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start + 1;
}
},
ArrayLiteral: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ,
elementLength = node.elements.length;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
}
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("@[");
else if (!elementLength)
buffer.concat("objj_msgSend(objj_msgSend(CPArray, \"alloc\"), \"init\")", node);
else
buffer.concat("objj_msgSend(objj_msgSend(CPArray, \"alloc\"), \"initWithObjects:count:\", [", node);
if (elementLength)
{
for (var i = 0; i < elementLength; i++)
{
var elt = node.elements[i];
if (i)
buffer.concat(", ");
if (!generate)
compiler.lastPos = elt.start;
compileNode(elt, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, elt.end));
}
if (!generateObjJ)
buffer.concat("], " + elementLength + ")");
}
if (generateObjJ)
buffer.concat("]");
if (!generate)
compiler.lastPos = node.end;
},
DictionaryLiteral: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ,
keyLength = node.keys.length;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
}
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
{
buffer.concat("@{");
for (var i = 0; i < keyLength; i++)
{
if (i !== 0)
buffer.concat(",");
compileNode(node.keys[i], state, "Expression");
buffer.concat(":");
compileNode(node.values[i], state, "Expression");
}
buffer.concat("}");
}
else if (!keyLength)
{
buffer.concat("objj_msgSend(objj_msgSend(CPDictionary, \"alloc\"), \"init\")", node);
}
else
{
buffer.concat("objj_msgSend(objj_msgSend(CPDictionary, \"alloc\"), \"initWithObjectsAndKeys:\"", node);
for (var i = 0; i < keyLength; i++)
{
var key = node.keys[i],
value = node.values[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = value.start;
compileNode(value, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, value.end));
buffer.concat(", ");
if (!generate)
compiler.lastPos = key.start;
compileNode(key, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, key.end));
}
buffer.concat(")");
}
if (!generate)
compiler.lastPos = node.end;
},
ImportStatement: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
isLocal = node.isLocal,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
if (generateObjJ)
{
buffer.concat("@import ");
buffer.concat(isLocal ? "\"" : "<");
buffer.concat(node.filename.value);
buffer.concat(isLocal ? "\"" : ">");
}
else
{
buffer.concat("objj_executeFile(\"", node);
buffer.concat(node.filename.value);
buffer.concat(isLocal ? "\", YES);" : "\", NO);");
}
if (!generate)
compiler.lastPos = node.end;
},
ClassDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
saveJSBuffer = compiler.jsBuffer,
className = node.classname.name,
classDef = compiler.getClassDef(className),
classScope = new Scope(state),
isInterfaceDeclaration = node.type === "InterfaceDeclarationStatement",
protocols = node.protocols,
generateObjJ = compiler.options.generateObjJ;
compiler.imBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
compiler.cmBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
// TODO: Check if this is needed
compiler.classBodyBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// First we declare the class
classDef = declareClass(compiler, node, classDef, className, isInterfaceDeclaration, generateObjJ, saveJSBuffer);
if (generateObjJ)
{
saveJSBuffer.concat(isInterfaceDeclaration ? "@interface " : "@implementation ");
saveJSBuffer.concat(className);
if (node.superclassname)
{
saveJSBuffer.concat(" : ");
compileNode(node.superclassname, state, "IdentifierName");
}
else if (node.categoryname)
{
saveJSBuffer.concat(" (");
compileNode(node.categoryname, state, "IdentifierName");
saveJSBuffer.concat(")");
}
}
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
{
if (generateObjJ)
{
if (i)
saveJSBuffer.concat(", ");
else
saveJSBuffer.concat(" <");
compileNode(protocols[i], state, "IdentifierName");
if (i === size - 1)
saveJSBuffer.concat(">");
}
else
{
saveJSBuffer.concat("\nvar aProtocol = objj_getProtocol(\"" + protocols[i].name + "\");", protocols[i]);
saveJSBuffer.concat("\nif (!aProtocol) throw new SyntaxError(\"*** Could not find definition for protocol \\\"" + protocols[i].name + "\\\"\");");
saveJSBuffer.concat("\nclass_addProtocol(the_class, aProtocol);");
}
}
}
classScope.classDef = classDef;
compiler.currentSuperClass = "objj_getClass(\"" + className + "\").super_class";
compiler.currentSuperMetaClass = "objj_getMetaClass(\"" + className + "\").super_class";
var firstIvarDeclaration = true,
hasAccessors = false;
// Now we add all ivars
if (node.ivardeclarations)
hasAccessors = addIvars(compiler, node, compileNode, state, classDef, className, classScope, firstIvarDeclaration, generateObjJ, saveJSBuffer);
if (generateObjJ)
{
indentation = indentation.substring(indentSize);
saveJSBuffer.concatFormat("\n}");
}
else if (!firstIvarDeclaration)
saveJSBuffer.concat("]);");
// If we have accessors add get and set methods for them
if (!generateObjJ && !isInterfaceDeclaration && hasAccessors)
generateGetterSetter(compiler, node);
// We will store the classDef first after accessors are done so we don't get a duplicate class error
compiler.classDefs[className] = classDef;
var bodies = node.body,
bodyLength = bodies.length;
if (bodyLength > 0)
{
var body;
if (!generate)
compiler.lastPos = bodies[0].start;
// And last add methods and other statements
for (var i = 0; i < bodyLength; i++)
{
body = bodies[i];
compileNode(body, classScope, "Statement");
}
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, body.end));
}
// We must make a new class object for our class definition if it's not a category
if (!generateObjJ && !isInterfaceDeclaration && !node.categoryname)
saveJSBuffer.concat("objj_registerClassPair(the_class);\n");
// Add instance methods
if (!generateObjJ && compiler.imBuffer.isEmpty())
{
saveJSBuffer.concat("class_addMethods(the_class, [");
saveJSBuffer.appendStringBuffer(compiler.imBuffer);
saveJSBuffer.concat("]);\n");
}
// Add class methods
if (!generateObjJ && compiler.cmBuffer.isEmpty())
{
saveJSBuffer.concat("class_addMethods(meta_class, [");
saveJSBuffer.appendStringBuffer(compiler.cmBuffer);
saveJSBuffer.concat("]);\n");
}
if (!generateObjJ)
saveJSBuffer.concat("}");
compiler.jsBuffer = saveJSBuffer;
// Skip the "@end"
if (!generate)
compiler.lastPos = node.end;
if (generateObjJ)
saveJSBuffer.concat("\n@end");
// If the class conforms to protocols check that all required methods are implemented
if (protocols)
checkProtocolConformance(compiler, node, classDef, protocols);
},
ProtocolDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
protocolName = node.protocolname.name,
protocolDef = compiler.getProtocolDef(protocolName),
protocols = node.protocols,
protocolScope = new Scope(state),
inheritFromProtocols = [],
generateObjJ = compiler.options.generateObjJ;
if (protocolDef)
throw compiler.syntaxError("Duplicate protocol " + protocolName, node.protocolname);
compiler.imBuffer = new StringBuffer();
compiler.cmBuffer = new StringBuffer();
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
if (generateObjJ)
{
buffer.concat("@protocol ");
compileNode(node.protocolname, state, "IdentifierName");
}
else
buffer.concat("{var the_protocol = objj_allocateProtocol(\"" + protocolName + "\");", node);
if (protocols)
{
if (generateObjJ)
buffer.concat(" <");
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i],
inheritFromProtocolName = protocol.name,
inheritProtocolDef = compiler.getProtocolDef(inheritFromProtocolName);
if (!inheritProtocolDef)
throw compiler.syntaxError("Can't find protocol " + inheritFromProtocolName, protocol);
if (generateObjJ)
{
if (i)
buffer.concat(", ");
compileNode(protocol, state, "IdentifierName");
}
else
{
buffer.concat("\nvar aProtocol = objj_getProtocol(\"" + inheritFromProtocolName + "\");", node);
buffer.concat("\nif (!aProtocol) throw new SyntaxError(\"*** Could not find definition for protocol \\\"" + protocolName + "\\\"\");", node);
buffer.concat("\nprotocol_addProtocol(the_protocol, aProtocol);", node);
}
inheritFromProtocols.push(inheritProtocolDef);
}
if (generateObjJ)
buffer.concat(">");
}
protocolDef = new ProtocolDef(protocolName, inheritFromProtocols);
compiler.protocolDefs[protocolName] = protocolDef;
protocolScope.protocolDef = protocolDef;
var someRequired = node.required;
if (someRequired)
{
var requiredLength = someRequired.length;
if (requiredLength > 0)
{
var required;
// We only add the required methods
for (var i = 0; i < requiredLength; i++)
{
required = someRequired[i];
if (!generate)
compiler.lastPos = required.start;
compileNode(required, protocolScope, "Statement");
}
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, required.end));
}
}
if (generateObjJ)
buffer.concatFormat("\n@end");
else
{
buffer.concat("\nobjj_registerProtocol(the_protocol);\n");
// Add instance methods
if (compiler.imBuffer.isEmpty())
{
buffer.concat("protocol_addMethodDescriptions(the_protocol, [");
buffer.atoms.push.apply(buffer.atoms, compiler.imBuffer.atoms); // FIXME: Move this append to StringBuffer
buffer.concat("], true, true);\n");
}
// Add class methods
if (compiler.cmBuffer.isEmpty())
{
buffer.concat("protocol_addMethodDescriptions(the_protocol, [");
buffer.atoms.push.apply(buffer.atoms, compiler.cmBuffer.atoms); // FIXME: Move this append to StringBuffer
buffer.concat("], true, false);\n");
}
buffer.concat("}");
}
compiler.jsBuffer = buffer;
// Skip @end
if (!generate)
compiler.lastPos = node.end;
},
IvarDeclaration: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer;
if (node.outlet)
buffer.concat("@outlet ");
compileNode(node.ivartype, state, "IdentifierName");
buffer.concat(" ");
compileNode(node.id, state, "IdentifierName");
if (node.accessors)
buffer.concat(" @accessors");
},
MethodDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
saveJSBuffer = compiler.jsBuffer,
methodScope = new Scope(state),
isInstanceMethodType = node.methodtype === "-",
selectors = node.selectors,
nodeArguments = node.arguments,
returnType = node.returntype,
// Return type is 'id' as default except if it is an action declared method, then it's 'void'
types = [returnType ? returnType.name : (node.action ? "void" : "id")],
returnTypeProtocols = returnType ? returnType.protocols : null,
selector = selectors[0].name, // There is always at least one selector
generateObjJ = compiler.options.generateObjJ;
if (returnTypeProtocols)
{
for (var i = 0, count = returnTypeProtocols.length; i < count; i++)
{
var returnTypeProtocol = returnTypeProtocols[i];
if (!compiler.getProtocolDef(returnTypeProtocol.name))
compiler.addWarning(createMessage("Cannot find protocol declaration for '" + returnTypeProtocol.name + "'", returnTypeProtocol, compiler.source));
}
}
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// If we are generating objective-J code write everything directly to the regular buffer
// Otherwise we have one for instance methods and one for class methods.
if (generateObjJ)
{
compiler.jsBuffer.concat(isInstanceMethodType ? "- (" : "+ (");
compiler.jsBuffer.concat(types[0]);
compiler.jsBuffer.concat(")");
}
else
compiler.jsBuffer = isInstanceMethodType ? compiler.imBuffer : compiler.cmBuffer;
// Put together the selector. Maybe this should be done in the parser...
// Or maybe we should do it here as when genereting Objective-J code it's kind of handy
if (nodeArguments.length > 0)
{
for (var i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i],
argumentType = argument.type,
argumentTypeName = argumentType ? argumentType.name : "id",
argumentProtocols = argumentType ? argumentType.protocols : null;
types.push(argumentTypeName);
if (i === 0)
selector += ":";
else
selector += (selectors[i] ? selectors[i].name : "") + ":";
if (argumentProtocols)
{
for (var j = 0, size = argumentProtocols.length; j < size; j++)
{
var argumentProtocol = argumentProtocols[j];
if (!compiler.getProtocolDef(argumentProtocol.name))
compiler.addWarning(createMessage("Cannot find protocol declaration for '" + argumentProtocol.name + "'", argumentProtocol, compiler.source));
}
}
if (generateObjJ)
{
var aSelector = selectors[i];
if (i)
compiler.jsBuffer.concat(" ");
compiler.jsBuffer.concat((aSelector ? aSelector.name : "") + ":");
compiler.jsBuffer.concat("(");
compiler.jsBuffer.concat(argumentTypeName);
if (argumentProtocols)
{
compiler.jsBuffer.concat(" <");
for (var j = 0, size = argumentProtocols.length; j < size; j++)
{
var argumentProtocol = argumentProtocols[j];
if (j)
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat(argumentProtocol.name);
}
compiler.jsBuffer.concat(">");
}
compiler.jsBuffer.concat(")");
compileNode(argument.identifier, state, "IdentifierName");
}
}
}
else if (generateObjJ)
{
var selector = selectors[0];
compiler.jsBuffer.concat(selector.name, selector);
}
if (generateObjJ)
{
if (node.parameters)
compiler.jsBuffer.concat(", ...");
}
else
{
if (compiler.jsBuffer.isEmpty()) // Add comma separator if this is not first method in this buffer
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat("new objj_method(sel_getUid(\"", node);
compiler.jsBuffer.concat(selector);
compiler.jsBuffer.concat("\"), ");
}
if (node.body)
{
if (!generateObjJ)
{
compiler.jsBuffer.concat("function");
if (compiler.options.generateMethodFunctionNames)
compiler.jsBuffer.concat(" $" + state.currentClassName() + "__" + selector.replace(/:/g, "_"));
compiler.jsBuffer.concat("(self, _cmd");
}
methodScope.methodType = node.methodtype;
if (nodeArguments)
{
for (var i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i],
argumentName = argument.identifier.name;
if (!generateObjJ)
{
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat(argumentName, argument.identifier);
}
methodScope.vars[argumentName] = {type: "method argument", node: argument};
}
}
if (!generateObjJ)
compiler.jsBuffer.concat(")\n");
if (!generate)
compiler.lastPos = node.startOfBody;
indentation += indentStep;
compileNode(node.body, methodScope, "Statement");
indentation = indentation.substring(indentSize);
if (!generate)
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.body.end));
if (!generateObjJ)
compiler.jsBuffer.concat("\n");
}
else // It is a interface or protocol declaration and we don't have a method implementation
{
if (generateObjJ)
compiler.jsBuffer.concat(";");
else
compiler.jsBuffer.concat("Nil\n");
}
if (!generateObjJ)
{
if (compiler.options.generateMethodArgumentTypeSignatures)
compiler.jsBuffer.concat(","+JSON.stringify(types));
compiler.jsBuffer.concat(")");
compiler.jsBuffer = saveJSBuffer;
}
if (!generate)
compiler.lastPos = node.end;
// Add the method to the class or protocol definition
var def = state.classDef,
alreadyDeclared;
// But first, if it is a class definition check if it is declared in the superclass or interface declaration
if (def)
alreadyDeclared = isInstanceMethodType ? def.getInstanceMethod(selector) : def.getClassMethod(selector);
else
def = state.protocolDef;
if (!def)
throw "Internal error: MethodDeclaration without ClassDeclaration or ProtocolDeclaration at line: " + exports.acorn.getLineInfo(compiler.source, node.start).line;
// Create warnings if types do not correspond to the method declaration in the superclass or interface declarations.
// If we don't find the method in the superclass or interface declarations above or if it is a protocol
// declaration, try to find it in any of the conforming protocols.
if (!alreadyDeclared)
{
var protocols = def.protocols;
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i],
alreadyDeclared = isInstanceMethodType ? protocol.getInstanceMethod(selector) : protocol.getClassMethod(selector);
if (alreadyDeclared)
break;
}
}
}
if (alreadyDeclared)
{
var declaredTypes = alreadyDeclared.types;
if (declaredTypes)
{
var typeSize = declaredTypes.length;
if (typeSize > 0)
{
// First type is return type
var declaredReturnType = declaredTypes[0];
// Create warning if return types are not the same.
// It is ok if superclass has 'id' and subclass has a class type.
if (declaredReturnType !== types[0] && !(declaredReturnType === "id" && returnType && returnType.typeisclass))
compiler.addWarning(createMessage("Conflicting return type in implementation of '" + selector + "': '" + declaredReturnType + "' vs '" + types[0] + "'", returnType || node.action || selectors[0], compiler.source));
// Check the parameter types. The size of the two type arrays
// should be the same as they have the same selector.
for (var i = 1; i < typeSize; i++)
{
var parameterType = declaredTypes[i];
if (parameterType !== types[i] && !(parameterType === "id" && nodeArguments[i - 1].type.typeisclass))
compiler.addWarning(createMessage("Conflicting parameter types in implementation of '" + selector + "': '" + parameterType + "' vs '" + types[i] + "'", nodeArguments[i - 1].type || nodeArguments[i - 1].identifier, compiler.source));
}
}
}
}
// Now we add it
var methodDef = new MethodDef(selector, types);
if (isInstanceMethodType)
def.addInstanceMethod(methodDef);
else
def.addClassMethod(methodDef);
},
MessageSendExpression: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.object ? node.object.start : (node.arguments.length ? node.arguments[0].start : node.end);
}
if (node.superObject)
{
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("[super ");
else
{
buffer.concat("objj_msgSendSuper(", node);
buffer.concat("{ receiver:self, super_class:" + (state.currentMethodType() === "+" ? compiler.currentSuperMetaClass : compiler.currentSuperClass ) + " }");
}
}
else
{
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("[", node);
else
buffer.concat("objj_msgSend(", node);
compileNode(node.object, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.object.end));
}
var selectors = node.selectors,
nodeArguments = node.arguments,
firstSelector = selectors[0],
// There is always at least one selector
selector = firstSelector ? firstSelector.name : "",
parameters = node.parameters;
if (generateObjJ)
{
for (var i = 0, size = nodeArguments.length; i < size || (size === 0 && i === 0); i++)
{
var sel = selectors[i];
buffer.concat(" ");
buffer.concat(sel ? sel.name : "");
if (size > 0)
{
var argument = nodeArguments[i];
buffer.concat(":");
compileNode(argument, state, "Expression");
}
}
if (parameters)
{
for (i = 0, size = parameters.length; i < size; i++)
{
var parameter = parameters[i];
buffer.concat(", ");
compileNode(parameter, state, "Expression");
}
}
buffer.concat("]");
}
else
{
// Put together the selector. Maybe this should be done in the parser...
for (var i = 0; i < nodeArguments.length; i++)
{
if (i === 0)
selector += ":";
else
selector += (selectors[i] ? selectors[i].name : "") + ":";
}
buffer.concat(", \"");
buffer.concat(selector); // FIXME: sel_getUid(selector + "") ? This FIXME is from the old preprocessor compiler
buffer.concat("\"");
if (nodeArguments)
{
for (i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = argument.start;
compileNode(argument, state, "Expression");
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, argument.end));
compiler.lastPos = argument.end;
}
}
}
if (parameters)
{
for (i = 0; i < parameters.length; i++)
{
var parameter = parameters[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = parameter.start;
compileNode(parameter, state, "Expression");
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, parameter.end));
compiler.lastPos = parameter.end;
}
}
}
buffer.concat(")");
}
if (!generate)
compiler.lastPos = node.end;
},
SelectorLiteralExpression: function(node, state)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Add an extra space if it looks something like this: "return(@selector(a:))". No space between return and expression.
buffer.concat(" ");
}
buffer.concat(generateObjJ ? "@selector(" : "sel_getUid(\"", node);
buffer.concat(node.selector);
buffer.concat(generateObjJ ? ")" : "\")");
if (!generate)
compiler.lastPos = node.end;
},
ProtocolLiteralExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(" "); // Add an extra space if it looks something like this: "return(@protocol(a))". No space between return and expression.
}
buffer.concat(generateObjJ ? "@protocol(" : "objj_getProtocol(\"", node);
compileNode(node.id, state, "IdentifierName");
buffer.concat(generateObjJ ? ")" : "\")");
if (!generate)
compiler.lastPos = node.end;
},
Reference: function(node, state)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(" "); // Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
}
if (generateObjJ)
{
buffer.concat("@ref(", node);
buffer.concat(node.element.name, node.element);
buffer.concat(")", node);
}
else
{
buffer.concat("function(__input) { if (arguments.length) return ", node);
buffer.concat(node.element.name);
buffer.concat(" = __input; return ");
buffer.concat(node.element.name);
buffer.concat("; }");
}
if (!generate)
compiler.lastPos = node.end;
},
Dereference: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
checkCanDereference(state, node.expr);
// @deref(y) -> y()
// @deref(@deref(y)) -> y()()
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.expr.start;
}
if (generateObjJ)
buffer.concat("@deref(");
compileNode(node.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.expr.end));
if (generateObjJ)
buffer.concat(")");
else
buffer.concat("()");
if (!generate)
compiler.lastPos = node.end;
},
ClassStatement: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!compiler.generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
buffer.concat("//");
}
if (generateObjJ)
{
buffer.concat("@class ");
compileNode(node.id, state, "IdentifierName");
}
var className = node.id.name;
if (!compiler.getClassDef(className))
compiler.classDefs[className] = new ClassDef(false, className);
state.vars[node.id.name] = {type: "class", node: node.id};
},
GlobalStatement: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!compiler.generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
buffer.concat("//");
}
if (generateObjJ)
{
buffer.concat("@global ");
compileNode(node.id, state, "IdentifierName");
}
state.rootScope().vars[node.id.name] = {type: "global", node: node.id};
},
PreprocessStatement: function(node, state)
{
var compiler = state.compiler;
if (!compiler.generate)
{
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
compiler.jsBuffer.concat("//");
}
}
}); // var codeGenerator = walk.make()
}); // function wrapper
| lib/compiler.js | /*
* compiler.j
*
* Created by Martin Carlberg.
* Copyright 2013, Martin Carlberg.
*
* Additional work by Aparajita Fishman.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the MIT license (http://opensource.org/licenses/MIT).
*/
/* global define, acorn, window, CFURL, Executable, FileDependency, objj_getClass, objj_getProtocol, class_copyIvarList, class_copyProtocolList, class_copyMethodList, class_getSuperclass, method_getName, protocol_getName, protocol_copyMethodDescriptionList */
(function(mod)
{
"use strict";
// CommonJS
if (typeof exports === "object" && typeof module === "object")
return mod(
exports,
require("objj-acorn/acorn"),
require("objj-acorn/util/walk"),
require("source-map"));
// AMD
if (typeof define === "function" && define.amd)
return define(
[
"exports",
"objj-acorn/acorn",
"objj-acorn/util/walk",
"source-map"
], mod);
// Browser
mod(this.objjCompiler || (this.objjCompiler = {}), acorn, acorn.walk, null);
})
(function(exports, acorn, walk, sourceMap)
{
"use strict";
exports.version = "0.5.0";
exports.acorn = acorn;
var reservedIdentifiers = acorn.makePredicate("self _cmd undefined localStorage arguments"),
wordPrefixOperators = acorn.makePredicate("delete in instanceof new typeof void"),
isLogicalOrBinaryExpression = acorn.makePredicate("LogicalExpression BinaryExpression");
// The compiler first uses acorn to generate an AST. It then walks the AST to generate either
// a list of file dependencies or JavaScript code. File dependencies generation is only used
// by the Objective-J loader and runtime.
var CompilerGenerateFileDependencies = 1,
CompilerGenerateCode = 2;
// Options may be passed to further configure the compiler. These options are recognized:
var defaultOptions = {
// Acorn (parser) options. For more information see objj-acorn.
// We use a function here to create a new object every time we copy the default options.
acornOptions: function() { return Object.create(null); },
// If true, generates a source map for the compiled file.
sourceMap: false,
// What to generate.
generateWhat: CompilerGenerateCode,
// Pass in class definitions. New class definitions in the source file will be added to this when compiling.
classDefs: function() { return Object.create(null); },
// Pass in protocol definitions. New protocol definitions in the source file will be added to this when compiling.
protocolDefs: function() { return Object.create(null); },
// If true, the compiler generates source code from the AST. If false, the compiler copies source code
// from the source file.
// WARNING: The preprocessor does not work if this is false.
generate: true,
// If true, the compiler generates Objective-J code instead of JavaScript code. Of course this is really
// only useful if you want the compiler to reformat/beautify the code.
generateObjJ: false,
// The compiler uses JSON format objects which determine how the source code is formatted.
// Example formats are located in the formats directory.
format: null,
// The string to use to indent. Defaults to a single space.
indentString: " ",
// How many indentStrings to use when indenting generated code.
indentWidth: 4,
// If true, comments are included when generating code and the acorn options
// trackComments and trackCommentsIncludeLineBreak are set true.
includeComments: false,
// We support this here as the old Objective-J compiler (Not a real compiler, Preprocessor.js) transformed
// named function declarations to assignments.
// Example: 'function f(x) { return x }' transforms to: 'f = function(x) { return x }'
transformNamedFunctionToAssignment: false,
// Objective-J methods are implemented as functions. If this option is true, the functions
// are named $<class>_<method>, where <class> is the class name, and <method> is the method name.
// If this option is false, the function is anonymous.
generateMethodFunctionNames: true,
// If true, the compiler generates type information for method arguments.
generateMethodArgumentTypeSignatures: true,
// If true, the compiler generates type information for ivars.
generateIvarTypeSignatures: true,
};
function setupOptions(options)
{
options = options || Object.create(null);
for (var option in defaultOptions)
{
if (!options.hasOwnProperty(option))
{
var defaultOption = defaultOptions[option];
options[option] = typeof defaultOption === "function" ? defaultOption() : defaultOption;
}
}
return options;
}
var Scope = function(prev, base)
{
this.vars = Object.create(null);
if (base)
for (var key in base)
this[key] = base[key];
this.prev = prev;
if (prev)
{
this.compiler = prev.compiler;
this.nodeStack = prev.nodeStack.slice(0);
this.nodePriorStack = prev.nodePriorStack.slice(0);
this.nodeStackOverrideType = prev.nodeStackOverrideType.slice(0);
}
else
{
this.nodeStack = [];
this.nodePriorStack = [];
this.nodeStackOverrideType = [];
}
};
Scope.prototype.toString = function()
{
return this.ivars ? "ivars: " + JSON.stringify(this.ivars) : "<No ivars>";
};
Scope.prototype.compiler = function()
{
return this.compiler;
};
Scope.prototype.rootScope = function()
{
return this.prev ? this.prev.rootScope() : this;
};
Scope.prototype.isRootScope = function()
{
return !this.prev;
};
Scope.prototype.currentClassName = function()
{
return this.classDef ? this.classDef.name : (this.prev ? this.prev.currentClassName() : null);
};
Scope.prototype.currentProtocolName = function()
{
return this.protocolDef ? this.protocolDef.name : (this.prev ? this.prev.currentProtocolName() : null);
};
Scope.prototype.getIvarForCurrentClass = function(/* String */ ivarName)
{
if (this.ivars)
{
var ivar = this.ivars[ivarName];
if (ivar)
return ivar;
}
var prev = this.prev;
// Stop at the class declaration
if (prev && !this.classDef)
return prev.getIvarForCurrentClass(ivarName);
return null;
};
Scope.prototype.getLvar = function(/* String */ lvarName, /* BOOL */ stopAtMethod)
{
if (this.vars)
{
var lvar = this.vars[lvarName];
if (lvar)
return lvar;
}
var prev = this.prev;
// Stop at the method declaration
if (prev && (!stopAtMethod || !this.methodType))
return prev.getLvar(lvarName, stopAtMethod);
return null;
};
Scope.prototype.currentMethodType = function()
{
return this.methodType ? this.methodType : (this.prev ? this.prev.currentMethodType() : null);
};
Scope.prototype.copyAddedSelfToIvarsToParent = function()
{
if (this.prev && this.addedSelfToIvars) for (var key in this.addedSelfToIvars)
{
var addedSelfToIvar = this.addedSelfToIvars[key],
scopeAddedSelfToIvar = (this.prev.addedSelfToIvars || (this.prev.addedSelfToIvars = Object.create(null)))[key] || (this.prev.addedSelfToIvars[key] = []);
// Append at end in parent scope
scopeAddedSelfToIvar.push.apply(scopeAddedSelfToIvar, addedSelfToIvar);
}
};
Scope.prototype.addMaybeWarning = function(warning)
{
var rootScope = this.rootScope();
(rootScope._maybeWarnings || (rootScope._maybeWarnings = [])).push(warning);
};
Scope.prototype.maybeWarnings = function()
{
return this.rootScope()._maybeWarnings;
};
Scope.prototype.pushNode = function(node, overrideType)
{
/*
Here we push 3 things onto a stack. The node, override type and an array
that can keep track of prior nodes on this level. The current node is also
pushed to the last prior array.
Special-case when the node is the same as the parent node. This happens
when using an override type when walking the AST. The same prior list is
then used instead of a new empty one.
*/
var nodePriorStack = this.nodePriorStack,
length = nodePriorStack.length,
lastPriorList = length ? nodePriorStack[length - 1] : null,
lastNode = length ? this.nodeStack[length - 1] : null;
// First add this node to the parent list of nodes, if it has one.
// If not the same node push the node.
if (lastPriorList && lastNode !== node)
lastPriorList.push(node);
// Use the last prior list if it is the same node
nodePriorStack.push(lastNode === node ? lastPriorList : []);
this.nodeStack.push(node);
this.nodeStackOverrideType.push(overrideType);
};
Scope.prototype.popNode = function()
{
this.nodeStackOverrideType.pop();
this.nodePriorStack.pop();
return this.nodeStack.pop();
};
Scope.prototype.currentNode = function()
{
var nodeStack = this.nodeStack;
return nodeStack[nodeStack.length - 1];
};
Scope.prototype.currentOverrideType = function()
{
var nodeStackOverrideType = this.nodeStackOverrideType;
return nodeStackOverrideType[nodeStackOverrideType.length - 1];
};
Scope.prototype.priorNode = function()
{
var nodePriorStack = this.nodePriorStack,
length = nodePriorStack.length;
if (length > 1)
{
var parent = nodePriorStack[length - 2];
return parent[parent.length - 2] || null;
}
return null;
};
Scope.prototype.format = function(index, format, useOverrideForNode)
{
var nodeStack = this.nodeStack,
length = nodeStack.length;
index = index || 0;
if (index >= length)
return null;
// Get the nodes backwards from the stack
var i = length - index - 1,
currentNode = nodeStack[i],
currentFormat = format || this.compiler.format,
// Get the parent descriptions except if no format was provided, then it is the root description
parentFormats = format ? format.parent : currentFormat,
nextFormat;
if (parentFormats)
{
var nodeType = useOverrideForNode === currentNode ? this.nodeStackOverrideType[i] : currentNode.type;
nextFormat = parentFormats[nodeType];
if (useOverrideForNode === currentNode && !nextFormat)
return null;
}
if (nextFormat)
{
// Check for more 'parent' attributes or return nextFormat
return this.format(index + 1, nextFormat);
}
else
{
// Check for a virtual node one step up in the stack
nextFormat = this.format(index + 1, format, currentNode);
if (nextFormat)
return nextFormat;
else
{
// Ok, we have found a format description (currentFormat).
// Lets check if we have any other descriptions dependent on the prior node.
var priorFormats = currentFormat.prior;
if (priorFormats)
{
var priorNode = this.priorNode(),
priorFormat = priorFormats[priorNode ? priorNode.type : "None"];
if (priorFormat)
return priorFormat;
}
return currentFormat;
}
}
};
var GlobalVariableMaybeWarning = function(/* String */ aMessage, /* SpiderMonkey AST node */ node, /* String */ code)
{
this.message = createMessage(aMessage, node, code);
this.node = node;
};
GlobalVariableMaybeWarning.prototype.checkIfWarning = function(/* Scope */ scope)
{
var identifier = this.node.name;
return !scope.getLvar(identifier) &&
typeof global[identifier] === "undefined" &&
(typeof window === "undefined" || typeof window[identifier] === "undefined") &&
!scope.compiler.getClassDef(identifier);
};
function StringBuffer(useSourceNode, file)
{
if (useSourceNode)
{
this.rootNode = new sourceMap.SourceNode();
this.concat = this.concatSourceNode;
this.toString = this.toStringSourceNode;
this.isEmpty = this.isEmptySourceNode;
this.appendStringBuffer = this.appendStringBufferSourceNode;
this.length = this.lengthSourceNode;
this.file = file;
}
else
{
this.atoms = [];
this.concat = this.concatString;
this.toString = this.toStringString;
this.isEmpty = this.isEmptyString;
this.appendStringBuffer = this.appendStringBufferString;
this.length = this.lengthString;
}
}
StringBuffer.prototype.toStringString = function()
{
return this.atoms.join("");
};
StringBuffer.prototype.toStringSourceNode = function()
{
return this.rootNode.toStringWithSourceMap({file: this.file});
};
StringBuffer.prototype.concatString = function(aString)
{
this.atoms.push(aString);
};
StringBuffer.prototype.concatSourceNode = function(aString, node)
{
if (node)
{
//console.log("Snippet: " + aString + ", line: " + node.loc.start.line + ", column: " + node.loc.start.column + ", source: " + node.loc.source);
this.rootNode.add(new sourceMap.SourceNode(node.loc.start.line, node.loc.start.column, node.loc.source, aString));
}
else
this.rootNode.add(aString);
if (this.notEmpty)
this.notEmpty = true;
};
// '\n' will indent. '\n\<N>' will indent or dedent by <N> levels.
StringBuffer.prototype.concatFormat = function(aString)
{
if (!aString)
return;
var lines = aString.split("\n"),
size = lines.length;
if (size > 1)
{
this.concat(lines[0]);
for (var i = 1; i < size; i++)
{
var line = lines[i];
this.concat("\n");
if (line.slice(0, 1) === "\\")
{
var numberLength = 1,
indent = line.slice(1, 1 + numberLength);
if (indent === "-")
{
numberLength = 2;
indent = line.slice(1, 1 + numberLength);
}
var indentationNumber = parseInt(indent, 10);
if (indentationNumber)
{
this.concat(indentationNumber > 0 ?
indentation + new Array(indentationNumber * indentWidth + 1).join(indentString) :
indentation.substring(indentSize * -indentationNumber));
}
line = line.slice(1 + numberLength);
}
else if (line || i === size - 1)
{
// Ident if there is something between line breaks or the last linebreak
this.concat(indentation);
}
if (line)
this.concat(line);
}
}
else
this.concat(aString);
};
StringBuffer.prototype.isEmptyString = function()
{
return this.atoms.length !== 0;
};
StringBuffer.prototype.isEmptySourceNode = function()
{
return !this.notEmpty;
};
StringBuffer.prototype.appendStringBufferString = function(stringBuffer)
{
this.atoms.push.apply(this.atoms, stringBuffer.atoms);
};
StringBuffer.prototype.appendStringBufferSourceNode = function(stringBuffer)
{
this.rootNode.add(stringBuffer.rootNode);
};
StringBuffer.prototype.lengthString = function()
{
return this.atoms.length;
};
StringBuffer.prototype.lengthSourceNode = function()
{
return this.rootNode.children.length;
};
/*
Both ClassDef and ProtocolDef conform to a 'protocol' (that we can't declare in Javascript).
Both have the attribute 'protocols': Array of ProtocolDef that they conform to.
Both also have the functions: addInstanceMethod, addClassMethod, getInstanceMethod and getClassMethod
classDef = {
"className": aClassName,
"superClass": superClass ,
"ivars": myIvars,
"instanceMethods": instanceMethodDefs,
"classMethods": classMethodDefs,
"protocols": myProtocols
};
*/
var ClassDef = function(isImplementationDeclaration, name, superClass, ivars, instanceMethods, classMethods, protocols)
{
this.name = name;
if (superClass)
this.superClass = superClass;
if (ivars)
this.ivars = ivars;
if (isImplementationDeclaration)
{
this.instanceMethods = instanceMethods || Object.create(null);
this.classMethods = classMethods || Object.create(null);
}
if (protocols)
this.protocols = protocols;
};
ClassDef.prototype.addInstanceMethod = function(methodDef) {
this.instanceMethods[methodDef.name] = methodDef;
};
ClassDef.prototype.addClassMethod = function(methodDef) {
this.classMethods[methodDef.name] = methodDef;
};
ClassDef.prototype.listOfNotImplementedMethodsForProtocols = function(protocolDefs)
{
var resultList = [],
instanceMethods = this.getInstanceMethods(),
classMethods = this.getClassMethods();
for (var i = 0, size = protocolDefs.length; i < size; i++)
{
var protocolDef = protocolDefs[i],
protocolInstanceMethods = protocolDef.requiredInstanceMethods,
protocolClassMethods = protocolDef.requiredClassMethods,
inheritFromProtocols = protocolDef.protocols,
methodName,
methodDef;
if (protocolInstanceMethods)
{
for (methodName in protocolInstanceMethods)
{
methodDef = protocolInstanceMethods[methodName];
if (!instanceMethods[methodName])
resultList.push({"methodDef": methodDef, "protocolDef": protocolDef});
}
}
if (protocolClassMethods)
{
for (methodName in protocolClassMethods)
{
methodDef = protocolClassMethods[methodName];
if (!classMethods[methodName])
resultList.push({"methodDef": methodDef, "protocolDef": protocolDef});
}
}
if (inheritFromProtocols)
resultList = resultList.concat(this.listOfNotImplementedMethodsForProtocols(inheritFromProtocols));
}
return resultList;
};
ClassDef.prototype.getInstanceMethod = function(name)
{
var instanceMethods = this.instanceMethods;
if (instanceMethods)
{
var method = instanceMethods[name];
if (method)
return method;
}
var superClass = this.superClass;
if (superClass)
return superClass.getInstanceMethod(name);
return null;
};
ClassDef.prototype.getClassMethod = function(name)
{
var classMethods = this.classMethods;
if (classMethods)
{
var method = classMethods[name];
if (method)
return method;
}
var superClass = this.superClass;
if (superClass)
return superClass.getClassMethod(name);
return null;
};
// Return a new Array with all instance methods
ClassDef.prototype.getInstanceMethods = function()
{
var instanceMethods = this.instanceMethods;
if (instanceMethods)
{
var superClass = this.superClass,
returnObject = Object.create(null),
methodName;
if (superClass)
{
var superClassMethods = superClass.getInstanceMethods();
for (methodName in superClassMethods)
returnObject[methodName] = superClassMethods[methodName];
}
for (methodName in instanceMethods)
returnObject[methodName] = instanceMethods[methodName];
return returnObject;
}
return [];
};
// Return a new Array with all class methods
ClassDef.prototype.getClassMethods = function()
{
var classMethods = this.classMethods;
if (classMethods)
{
var superClass = this.superClass,
returnObject = Object.create(null),
methodName;
if (superClass)
{
var superClassMethods = superClass.getClassMethods();
for (methodName in superClassMethods)
returnObject[methodName] = superClassMethods[methodName];
}
for (methodName in classMethods)
returnObject[methodName] = classMethods[methodName];
return returnObject;
}
return [];
};
/*
protocolDef = {
"name": aProtocolName,
"protocols": inheritFromProtocols,
"requiredInstanceMethods": requiredInstanceMethodDefs,
"requiredClassMethods": requiredClassMethodDefs
};
*/
var ProtocolDef = function(name, protocols, requiredInstanceMethodDefs, requiredClassMethodDefs)
{
this.name = name;
this.protocols = protocols;
if (requiredInstanceMethodDefs)
this.requiredInstanceMethods = requiredInstanceMethodDefs;
if (requiredClassMethodDefs)
this.requiredClassMethods = requiredClassMethodDefs;
};
ProtocolDef.prototype.addInstanceMethod = function(methodDef)
{
(this.requiredInstanceMethods || (this.requiredInstanceMethods = Object.create(null)))[methodDef.name] = methodDef;
};
ProtocolDef.prototype.addClassMethod = function(methodDef)
{
(this.requiredClassMethods || (this.requiredClassMethods = Object.create(null)))[methodDef.name] = methodDef;
};
ProtocolDef.prototype.getInstanceMethod = function(name)
{
var instanceMethods = this.requiredInstanceMethods,
method;
if (instanceMethods)
{
method = instanceMethods[name];
if (method)
return method;
}
var protocols = this.protocols;
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i];
method = protocol.getInstanceMethod(name);
if (method)
return method;
}
return null;
};
ProtocolDef.prototype.getClassMethod = function(name)
{
var classMethods = this.requiredClassMethods,
method;
if (classMethods)
{
method = classMethods[name];
if (method)
return method;
}
var protocols = this.protocols;
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i];
method = protocol.getInstanceMethod(name);
if (method)
return method;
}
return null;
};
// methodDef = {"types": types, "name": selector}
var MethodDef = function(name, types)
{
this.name = name;
this.types = types;
};
var Compiler = function(/*String*/ source, /*String*/ url, options)
{
this.source = source;
this.URL = typeof CFURL !== "undefined" ? new CFURL(url) : url;
this.options = options = setupOptions(options);
this.generateWhat = options.generateWhat;
this.classDefs = options.classDefs;
this.protocolDefs = options.protocolDefs;
this.generate = options.generate;
this.createSourceMap = options.sourceMap;
this.format = options.format;
this.includeComments = options.includeComments;
this.transformNamedFunctionToAssignment = options.transformNamedFunctionToAssignment;
this.jsBuffer = new StringBuffer(this.createSourceMap, url);
this.imBuffer = null;
this.cmBuffer = null;
this.dependencies = [];
this.warnings = [];
this.lastPos = 0;
var acornOptions = options.acornOptions;
if (!acornOptions.sourceFile)
acornOptions.sourceFile = this.URL;
if (options.sourceMap && !acornOptions.locations)
acornOptions.locations = true;
// We never want (line:column) in the error messages
acornOptions.lineNoInErrorMessage = false;
try
{
this.AST = acorn.parse(this.source, options.acornOptions);
}
catch (e)
{
if (e.lineStart)
{
var message = this.prettifyMessage(e, "ERROR");
console.log(message);
}
throw e;
}
var compiler = compile,
generator;
if (this.generateWhat === CompilerGenerateCode)
{
generator = codeGenerator;
if (options.includeComments || options.format)
compiler = compileWithFormat;
}
else
generator = dependencyCollector;
compiler(this.AST, new Scope(null, {compiler: this}), generator);
if (this.createSourceMap)
{
var s = this.jsBuffer.toString();
this.compiledCode = s.code;
this.sourceMap = s.map;
}
else
{
this.compiledCode = this.jsBuffer.toString();
}
};
Compiler.importStack = [];
exports.compileToExecutable = function(/*String*/ source, /*CFURL*/ url, options)
{
Compiler.currentCompileFile = url;
return new Compiler(source, url, options).executable();
};
exports.compileToIMBuffer = function(/*String*/ source, /*CFURL*/ url, classDefs, protocolDefs)
{
var options = { classDefs: classDefs, protocolDefs: protocolDefs };
return new Compiler(source, url, options).IMBuffer();
};
exports.compile = function(/*String*/ source, /*CFURL*/ url, options)
{
return new Compiler(source, url, options);
};
exports.compileFileDependencies = function(/*String*/ source, /*CFURL*/ url, options)
{
Compiler.currentCompileFile = url;
(options || (options = {})).generateWhat = CompilerGenerateFileDependencies;
return new Compiler(source, url, options).executable();
};
Compiler.prototype.addWarning = function(/* Warning */ aWarning)
{
this.warnings.push(aWarning);
};
Compiler.prototype.getIvarForClass = function(/* String */ ivarName, /* Scope */ scope)
{
var ivar = scope.getIvarForCurrentClass(ivarName);
if (ivar)
return ivar;
var c = this.getClassDef(scope.currentClassName());
while (c)
{
var ivars = c.ivars;
if (ivars)
{
var ivarDef = ivars[ivarName];
if (ivarDef)
return ivarDef;
}
c = c.superClass;
}
};
Compiler.prototype.getClassDef = function(/* String */ aClassName)
{
if (!aClassName)
return null;
var c = this.classDefs[aClassName];
if (c)
return c;
if (typeof objj_getClass === "function")
{
var aClass = objj_getClass(aClassName);
if (aClass)
{
var ivars = class_copyIvarList(aClass),
ivarSize = ivars.length,
myIvars = Object.create(null),
protocols = class_copyProtocolList(aClass),
protocolSize = protocols.length,
myProtocols = Object.create(null),
instanceMethodDefs = Compiler.methodDefsFromMethodList(class_copyMethodList(aClass)),
classMethodDefs = Compiler.methodDefsFromMethodList(class_copyMethodList(aClass.isa)),
superClass = class_getSuperclass(aClass);
for (var i = 0; i < ivarSize; i++)
{
var ivar = ivars[i];
myIvars[ivar.name] = {"type": ivar.type, "name": ivar.name};
}
for (i = 0; i < protocolSize; i++)
{
var protocol = protocols[i],
protocolName = protocol_getName(protocol),
protocolDef = this.getProtocolDef(protocolName);
myProtocols[protocolName] = protocolDef;
}
c = new ClassDef(true, aClassName, superClass ? this.getClassDef(superClass.name) : null,
myIvars, instanceMethodDefs, classMethodDefs, myProtocols);
this.classDefs[aClassName] = c;
return c;
}
}
return null;
};
Compiler.prototype.getProtocolDef = function(/* String */ aProtocolName)
{
if (!aProtocolName)
return null;
var p = this.protocolDefs[aProtocolName];
if (p)
return p;
if (typeof objj_getProtocol === "function")
{
var aProtocol = objj_getProtocol(aProtocolName);
if (aProtocol)
{
var protocolName = protocol_getName(aProtocol),
requiredInstanceMethods = protocol_copyMethodDescriptionList(aProtocol, true, true),
requiredInstanceMethodDefs = Compiler.methodDefsFromMethodList(requiredInstanceMethods),
requiredClassMethods = protocol_copyMethodDescriptionList(aProtocol, true, false),
requiredClassMethodDefs = Compiler.methodDefsFromMethodList(requiredClassMethods),
protocols = aProtocol.protocols,
inheritFromProtocols = [];
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
inheritFromProtocols.push(this.getProtocolDef(protocols[i].name));
}
p = new ProtocolDef(protocolName, inheritFromProtocols, requiredInstanceMethodDefs, requiredClassMethodDefs);
this.protocolDefs[aProtocolName] = p;
return p;
}
}
return null;
};
Compiler.methodDefsFromMethodList = function(/* Array */ methodList)
{
var methodSize = methodList.length,
myMethods = Object.create(null);
for (var i = 0; i < methodSize; i++)
{
var method = methodList[i],
methodName = method_getName(method);
myMethods[methodName] = new MethodDef(methodName, method.types);
}
return myMethods;
};
// FIXME: Does not work any more
Compiler.prototype.executable = function()
{
if (!this._executable)
this._executable = new Executable(this.jsBuffer ? this.jsBuffer.toString() : null,
this.dependencies, this.URL, null, this);
return this._executable;
};
Compiler.prototype.IMBuffer = function()
{
return this.imBuffer;
};
Compiler.prototype.code = function()
{
return this.compiledCode;
};
Compiler.prototype.ast = function()
{
return JSON.stringify(this.AST, null, indentWidth);
};
Compiler.prototype.map = function()
{
return JSON.stringify(this.sourceMap);
};
Compiler.prototype.prettifyMessage = function(/* Message */ aMessage, /* String */ messageType)
{
var line = this.source.substring(aMessage.lineStart, aMessage.lineEnd),
message = "\n" + line;
message += (new Array(aMessage.column + 1)).join(" ");
message += (new Array(Math.min(1, line.length) + 1)).join("^") + "\n";
message += messageType + " line " + aMessage.line + " in " + this.URL + ": " + aMessage.message;
return message;
};
Compiler.prototype.syntaxError = function(message, node)
{
var pos = acorn.getLineInfo(this.source, node.start),
error = {
message: message,
line: pos.line,
column: pos.column,
lineStart: pos.lineStart,
lineEnd: pos.lineEnd
};
return new SyntaxError(this.prettifyMessage(error, "ERROR"));
};
Compiler.prototype.pushImport = function(url)
{
// This is used to keep track of imports. Each time the compiler imports a file the url is pushed here.
Compiler.importStack.push(url);
};
Compiler.prototype.popImport = function()
{
Compiler.importStack.pop();
};
function createMessage(/* String */ aMessage, /* SpiderMonkey AST node */ node, /* String */ code)
{
var message = acorn.getLineInfo(code, node.start);
message.message = aMessage;
return message;
}
function compile(node, state, visitor)
{
function compileNode(node, state, override)
{
visitor[override || node.type](node, state, compileNode);
}
compileNode(node, state);
}
function compileWithFormat(node, state, visitor)
{
var lastNode, lastComment;
function compileNode(node, state, override)
{
var compiler = state.compiler,
includeComments = compiler.includeComments,
localLastNode = lastNode,
sameNode = localLastNode === node,
i;
lastNode = node;
if (includeComments && !sameNode && node.commentsBefore && node.commentsBefore !== lastComment)
{
for (i = 0; i < node.commentsBefore.length; i++)
compiler.jsBuffer.concat(node.commentsBefore[i]);
}
state.pushNode(node, override);
var format = state.format();
//console.log("format: " + JSON.stringify(format) + ", node.type: " + node.type + ", override: " + override);
if (!sameNode && format && format.before)
compiler.jsBuffer.concatFormat(format.before);
visitor[override || node.type](node, state, compileNode, format);
if (!sameNode && format && format.after)
compiler.jsBuffer.concatFormat(format.after);
state.popNode();
if (includeComments && !sameNode && node.commentsAfter)
{
for (i = 0; i < node.commentsAfter.length; i++)
compiler.jsBuffer.concat(node.commentsAfter[i]);
lastComment = node.commentsAfter;
}
else
lastComment = null;
}
compileNode(node, state);
}
function isIdempotentExpression(node)
{
/* jshint -W004 */
switch (node.type)
{
case "Literal":
case "Identifier":
return true;
case "ArrayExpression":
for (var i = 0; i < node.elements.length; ++i)
{
if (!isIdempotentExpression(node.elements[i]))
return false;
}
return true;
case "DictionaryLiteral":
for (var i = 0; i < node.keys.length; ++i)
{
if (!isIdempotentExpression(node.keys[i]))
return false;
if (!isIdempotentExpression(node.values[i]))
return false;
}
return true;
case "ObjectExpression":
for (var i = 0; i < node.properties.length; ++i)
if (!isIdempotentExpression(node.properties[i].value))
return false;
return true;
case "FunctionExpression":
for (var i = 0; i < node.params.length; ++i)
if (!isIdempotentExpression(node.params[i]))
return false;
return true;
case "SequenceExpression":
for (var i = 0; i < node.expressions.length; ++i)
if (!isIdempotentExpression(node.expressions[i]))
return false;
return true;
case "UnaryExpression":
return isIdempotentExpression(node.argument);
case "BinaryExpression":
return isIdempotentExpression(node.left) && isIdempotentExpression(node.right);
case "ConditionalExpression":
return isIdempotentExpression(node.test) && isIdempotentExpression(node.consequent) && isIdempotentExpression(node.alternate);
case "MemberExpression":
return isIdempotentExpression(node.object) && (!node.computed || isIdempotentExpression(node.property));
case "Dereference":
return isIdempotentExpression(node.expr);
case "Reference":
return isIdempotentExpression(node.element);
default:
return false;
}
}
// We do not allow dereferencing of expressions with side effects because
// we might need to evaluate the expression twice in certain uses of deref,
// which is not obvious when you look at the deref operator in plain code.
function checkCanDereference(state, node)
{
if (!isIdempotentExpression(node))
throw state.compiler.syntaxError("Dereference of expression with side effects", node);
}
function parenthesize(compileNode)
{
return function(node, state, override, format)
{
state.compiler.jsBuffer.concat("(");
compileNode(node, state, override, format);
state.compiler.jsBuffer.concat(")");
};
}
function parenthesizeExpression(generate, node, subnode, state, compileNode, right)
{
(generate && subnodeHasPrecedence(node, subnode, right) ? parenthesize(compileNode) : compileNode)(subnode, state, "Expression");
}
function getAccessorInfo(accessors, ivarName)
{
var property = (accessors.property && accessors.property.name) || ivarName,
getter = (accessors.getter && accessors.getter.name) || property;
return { property: property, getter: getter };
}
var operatorPrecedence = {
// MemberExpression
// These two are never used, since the "computed" attribute of the MemberExpression
// determines which one to use.
// ".": 0, "[]": 0,
// NewExpression
// This is never used.
// "new": 1,
// All these are UnaryExpression or UpdateExpression and are never used.
//"!": 2, "~": 2, "-": 2, "+": 2, "++": 2, "--": 2, "typeof": 2, "void": 2, "delete": 2,
// BinaryExpression
"*": 3, "/": 3, "%": 3,
"+": 4, "-": 4,
"<<": 5, ">>": 5, ">>>": 5,
"<": 6, "<=": 6, ">": 6, ">=": 6, "in": 6, "instanceof": 6,
"==": 7, "!=": 7, "===": 7, "!==": 7,
"&": 8,
"^": 9,
"|": 10,
// LogicalExpression
"&&": 11,
"||": 12
// ConditionalExpression
// AssignmentExpression
};
var expressionTypePrecedence = {
MemberExpression: 0,
CallExpression: 1,
NewExpression: 2,
FunctionExpression: 3,
UnaryExpression: 4, UpdateExpression: 4,
BinaryExpression: 5,
LogicalExpression: 6,
ConditionalExpression: 7,
AssignmentExpression: 8
};
// Returns true if subnode has higher precedence than node.
// If subnode is the right subnode of a binary expression, right is true.
function subnodeHasPrecedence(node, subnode, right)
{
var nodeType = node.type,
nodePrecedence = expressionTypePrecedence[nodeType] || -1,
subnodePrecedence = expressionTypePrecedence[subnode.type] || -1,
nodeOperatorPrecedence,
subnodeOperatorPrecedence;
return subnodePrecedence > nodePrecedence ||
(nodePrecedence === subnodePrecedence && isLogicalOrBinaryExpression(nodeType) &&
((subnodeOperatorPrecedence = operatorPrecedence[subnode.operator]) > (nodeOperatorPrecedence = operatorPrecedence[node.operator]) ||
(right === true && nodeOperatorPrecedence === subnodeOperatorPrecedence)
)
);
}
var indentString = defaultOptions.indentString,
indentWidth = defaultOptions.indentWidth,
indentSize = indentWidth * indentString.length,
indentStep = new Array(indentWidth + 1).join(indentString),
indentation = "";
// Helper for codeGenerator.ClassDeclarationStatement
function declareClass(compiler, node, classDef, className, isInterfaceDeclaration, generateObjJ, saveJSBuffer) // -> classDef
{
if (node.superclassname)
{
// To be an @implementation declaration it must have method and ivar dictionaries.
// If there are neither, it's a @class declaration. If there is no ivar dictionary,
// it's an @interface declaration.
// TODO: Create a ClassDef object and add this logic to it
if (classDef && classDef.ivars)
// It has a real implementation declaration already
throw compiler.syntaxError("Duplicate class " + className, node.classname);
if (isInterfaceDeclaration && classDef && classDef.instanceMethods && classDef.classMethods)
// It has a interface declaration already
throw compiler.syntaxError("Duplicate interface definition for class " + className, node.classname);
var superClassDef = compiler.getClassDef(node.superclassname.name);
if (!superClassDef)
{
var errorMessage = "Can't find superclass " + node.superclassname.name;
for (var i = Compiler.importStack.length; --i >= 0;)
errorMessage += "\n" + new Array((Compiler.importStack.length - i) * 2 + 1).join(" ") + "Imported by: " + Compiler.importStack[i];
throw compiler.syntaxError(errorMessage, node.superclassname);
}
classDef = new ClassDef(!isInterfaceDeclaration, className, superClassDef, Object.create(null));
if (!generateObjJ)
saveJSBuffer.concat("{var the_class = objj_allocateClassPair(" + node.superclassname.name + ", \"" + className + "\"),\nmeta_class = the_class.isa;", node);
}
else if (node.categoryname)
{
classDef = compiler.getClassDef(className);
if (!classDef)
throw compiler.syntaxError("Class " + className + " not found ", node.classname);
if (!generateObjJ)
{
saveJSBuffer.concat("{\nvar the_class = objj_getClass(\"" + className + "\")\n", node);
saveJSBuffer.concat("if (!the_class) throw new SyntaxError(\"*** Could not find definition for class \\\"" + className + "\\\"\");\n");
saveJSBuffer.concat("var meta_class = the_class.isa;");
}
}
else
{
classDef = new ClassDef(!isInterfaceDeclaration, className, null, Object.create(null));
if (!generateObjJ)
saveJSBuffer.concat("{var the_class = objj_allocateClassPair(Nil, \"" + className + "\"),\nmeta_class = the_class.isa;", node);
}
return classDef;
}
// Helper for codeGenerator.ClassDeclarationStatement
function addIvars(compiler, node, compileNode, state, classDef, className, classScope, firstIvarDeclaration, generateObjJ, saveJSBuffer) // -> hasAccessors
{
var hasAccessors = false;
if (generateObjJ)
{
saveJSBuffer.concat("{");
indentation += indentStep;
}
for (var i = 0; i < node.ivardeclarations.length; i++)
{
var ivarDecl = node.ivardeclarations[i],
ivarType = ivarDecl.ivartype ? ivarDecl.ivartype.name : null,
ivarIdentifier = ivarDecl.id,
ivarName = ivarIdentifier.name,
ivars = classDef.ivars,
ivar = {"type": ivarType, "name": ivarName},
accessors = ivarDecl.accessors;
if (ivars[ivarName])
throw compiler.syntaxError("Instance variable '" + ivarName + "'is already declared for class " + className, ivarIdentifier);
if (generateObjJ)
compileNode(ivarDecl, state, "IvarDeclaration");
else
{
if (firstIvarDeclaration)
{
firstIvarDeclaration = false;
saveJSBuffer.concat("class_addIvars(the_class, [");
}
else
saveJSBuffer.concat(", ");
if (compiler.options.generateIvarTypeSignatures)
saveJSBuffer.concat("new objj_ivar(\"" + ivarName + "\", \"" + ivarType + "\")", node);
else
saveJSBuffer.concat("new objj_ivar(\"" + ivarName + "\")", node);
}
if (ivarDecl.outlet)
ivar.outlet = true;
ivars[ivarName] = ivar;
if (!classScope.ivars)
classScope.ivars = Object.create(null);
classScope.ivars[ivarName] = {type: "ivar", name: ivarName, node: ivarIdentifier, ivar: ivar};
if (accessors)
{
var info = getAccessorInfo(accessors, ivarName),
property = info.property,
getterName = info.getter;
classDef.addInstanceMethod(new MethodDef(getterName, [ivarType]));
if (!accessors.readonly)
{
var setterName = accessors.setter ? accessors.setter.name : null;
if (!setterName)
{
var start = property.charAt(0) === "_" ? 1 : 0;
setterName = (start ? "_" : "") + "set" + property.substr(start, 1).toUpperCase() + property.substring(start + 1) + ":";
}
classDef.addInstanceMethod(new MethodDef(setterName, ["void", ivarType]));
}
hasAccessors = true;
}
}
return hasAccessors;
}
// Helper for codeGenerator.ClassDeclarationStatement
function generateGetterSetter(compiler, node)
{
var getterSetterBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
// Add the class declaration to compile accessors correctly
getterSetterBuffer.concat(compiler.source.substring(node.start, node.endOfIvars));
getterSetterBuffer.concat("\n");
for (var i = 0; i < node.ivardeclarations.length; i++)
{
var ivarDecl = node.ivardeclarations[i],
ivarType = ivarDecl.ivartype ? ivarDecl.ivartype.name : null,
ivarName = ivarDecl.id.name,
accessors = ivarDecl.accessors;
if (!accessors)
continue;
var info = getAccessorInfo(accessors, ivarName),
property = info.property,
getterName = info.getter,
getterCode = "- (" + (ivarType ? ivarType : "id") + ")" + getterName + "\n{\nreturn " + ivarName + ";\n}\n";
getterSetterBuffer.concat(getterCode);
if (accessors.readonly)
continue;
var setterName = accessors.setter ? accessors.setter.name : null;
if (!setterName)
{
var start = property.charAt(0) === "_" ? 1 : 0;
setterName = (start ? "_" : "") + "set" + property.substr(start, 1).toUpperCase() + property.substring(start + 1) + ":";
}
var setterCode = "- (void)" + setterName + "(" + (ivarType ? ivarType : "id") + ")newValue\n{\n";
if (accessors.copy)
setterCode += "if (" + ivarName + " !== newValue)\n" + ivarName + " = [newValue copy];\n}\n";
else
setterCode += ivarName + " = newValue;\n}\n";
getterSetterBuffer.concat(setterCode);
}
getterSetterBuffer.concat("\n@end");
// Remove all @accessors or we will get an infinite loop
var source = getterSetterBuffer.toString().replace(/@accessors(\(.*\))?/g, ""),
imBuffer = exports.compileToIMBuffer(source, "Accessors", compiler.classDefs, compiler.protocolDefs);
// Add the accessor methods first to the instance method buffer.
// This will allow manually added set and get methods to override the compiler generated methods.
compiler.imBuffer.concat(imBuffer);
}
function checkProtocolConformance(compiler, node, classDef, protocols)
{
// Lookup the protocolDefs for the protocols
var protocolDefs = [];
for (var i = 0, size = protocols.length; i < size; i++)
protocolDefs.push(compiler.getProtocolDef(protocols[i].name));
var unimplementedMethods = classDef.listOfNotImplementedMethodsForProtocols(protocolDefs);
if (unimplementedMethods && unimplementedMethods.length > 0)
{
for (i = 0, size = unimplementedMethods.length; i < size; i++)
{
var unimplementedMethod = unimplementedMethods[i],
methodDef = unimplementedMethod.methodDef,
protocolDef = unimplementedMethod.protocolDef;
compiler.addWarning(createMessage("Method '" + methodDef.name + "' in protocol '" + protocolDef.name + "' is not implemented", node.classname, compiler.source));
}
}
}
var dependencyCollector = walk.make(
{
ImportStatement: function(node, state)
{
var urlString = node.filename.value;
if (typeof FileDependency !== "undefined")
state.compiler.dependencies.push(new FileDependency(new CFURL(urlString), node.isLocal));
else
state.compiler.dependencies.push(urlString);
}
});
var codeGenerator = walk.make({
Program: function(node, state, compileNode)
{
var compiler = state.compiler;
indentString = compiler.options.indentString;
indentWidth = compiler.options.indentWidth;
indentSize = indentWidth * indentString.length;
indentStep = new Array(indentWidth + 1).join(indentString);
indentation = "";
for (var i = 0; i < node.body.length; ++i)
compileNode(node.body[i], state, "Statement");
if (!compiler.generate)
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.end));
// Check for warnings
var maybeWarnings = state.maybeWarnings();
if (maybeWarnings)
{
for (i = 0; i < maybeWarnings.length; i++)
{
var maybeWarning = maybeWarnings[i];
if (maybeWarning.checkIfWarning(state))
compiler.addWarning(maybeWarning.message);
}
}
},
BlockStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
skipIndentation = state.skipIndentation,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("{");
buffer.concatFormat(format.afterLeftBrace);
}
else
{
if (skipIndentation)
delete state.skipIndentation;
else
buffer.concat(indentation.substring(indentSize));
buffer.concat("{\n");
}
}
for (var i = 0; i < node.body.length; ++i)
compileNode(node.body[i], state, "Statement");
if (compiler.generate)
{
if (format)
{
buffer.concatFormat(format.beforeRightBrace);
buffer.concat("}");
}
else
{
buffer.concat(indentation.substring(indentSize));
buffer.concat("}");
if (!skipIndentation && state.isDecl !== false)
buffer.concat("\n");
state.indentBlockLevel--;
}
}
},
ExpressionStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate && !format;
if (generate)
compiler.jsBuffer.concat(indentation);
compileNode(node.expression, state, "Expression");
if (generate)
compiler.jsBuffer.concat(";\n");
},
IfStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("if", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
// Keep the 'else' and 'if' on the same line if it is an 'else if'
if (!state.superNodeIsElse)
buffer.concat(indentation);
else
delete state.superNodeIsElse;
buffer.concat("if (", node);
}
}
compileNode(node.test, state, "Expression");
if (compiler.generate)
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
var expressionClose = node.consequent.type === "EmptyStatement" ? ");" : ")";
if (format)
{
buffer.concat(expressionClose);
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(expressionClose + "\n");
}
indentation += indentStep;
compileNode(node.consequent, state, "Statement");
indentation = indentation.substring(indentSize);
var alternate = node.alternate;
if (alternate)
{
var alternateNotIf = alternate.type !== "IfStatement";
if (compiler.generate)
{
var emptyStatement = alternate.type === "EmptyStatement",
elseClause = emptyStatement ? "else;" : "else";
if (format)
{
buffer.concatFormat(format.beforeElse); // Do we need this?
buffer.concat(elseClause);
buffer.concatFormat(format.afterElse);
}
else
{
buffer.concat(indentation + elseClause);
buffer.concat(alternateNotIf ? "\n" : " ");
}
}
if (alternateNotIf)
indentation += indentStep;
else
state.superNodeIsElse = true;
compileNode(alternate, state, "Statement");
if (alternateNotIf)
indentation = indentation.substring(indentSize);
}
},
LabeledStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
compileNode(node.label, state, "IdentifierName");
if (format)
{
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(": ");
}
compileNode(node.body, state, "Statement");
},
BreakStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var label = node.label,
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
if (label)
{
if (format)
{
buffer.concat("break", node);
buffer.concatFormat(format.beforeLabel);
}
else
buffer.concat("break ", node);
compileNode(label, state, "IdentifierName");
if (!format)
buffer.concat(";\n");
}
else
buffer.concat(format ? "break" : "break;\n", node);
}
},
ContinueStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var label = node.label,
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
if (label)
{
if (format)
{
buffer.concat("continue", node);
buffer.concatFormat(format.beforeLabel);
}
else
buffer.concat("continue ", node);
compileNode(label, state, "IdentifierName");
if (!format)
buffer.concat(";\n");
}
else
buffer.concat(format ? "continue" : "continue;\n", node);
}
},
WithStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
buffer;
if (compiler.generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("with", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("with(", node);
}
}
compileNode(node.object, state, "Expression");
if (compiler.generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(")\n");
}
indentation += indentStep;
compileNode(node.body, state, "Statement");
indentation = indentation.substring(indentSize);
},
SwitchStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("switch", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(", node);
}
else
{
buffer.concat(indentation);
buffer.concat("switch (", node);
}
}
compileNode(node.discriminant, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
buffer.concat("{");
buffer.concatFormat(format.afterLeftBrace);
}
else
buffer.concat(") {\n");
}
indentation += indentStep;
for (var i = 0; i < node.cases.length; ++i)
{
var cs = node.cases[i];
if (cs.test)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCase);
buffer.concat("case", node);
buffer.concatFormat(format.afterCase);
}
else
{
buffer.concat(indentation);
buffer.concat("case ");
}
}
compileNode(cs.test, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(":\n");
}
}
else if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCase);
buffer.concat("default");
buffer.concatFormat(format.afterCase);
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat("default:\n");
}
indentation += indentStep;
for (var j = 0; j < cs.consequent.length; ++j)
compileNode(cs.consequent[j], state, "Statement");
indentation = indentation.substring(indentSize);
}
indentation = indentation.substring(indentSize);
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeRightBrace);
buffer.concat("}");
}
else
{
buffer.concat(indentation);
buffer.concat("}\n");
}
}
},
ReturnStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
buffer.concat("return", node);
}
if (node.argument)
{
if (generate)
buffer.concatFormat(format ? format.beforeExpression : " ");
compileNode(node.argument, state, "Expression");
}
if (generate && !format)
buffer.concat(";\n");
},
ThrowStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format)
buffer.concat(indentation);
buffer.concat("throw", node);
buffer.concatFormat(format ? format.beforeExpression : " ");
}
compileNode(node.argument, state, "Expression");
if (generate && !format)
buffer.concat(";\n");
},
TryStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (!format) buffer.concat(indentation);
buffer.concat("try", node);
buffer.concatFormat(format ? format.beforeStatement : " ");
}
indentation += indentStep;
if (!format)
state.skipIndentation = true;
compileNode(node.block, state, "Statement");
indentation = indentation.substring(indentSize);
if (node.handler)
{
var handler = node.handler,
inner = new Scope(state),
param = handler.param,
name = param.name;
inner.vars[name] = {type: "catch clause", node: param};
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCatch);
buffer.concat("catch");
buffer.concatFormat(format.afterCatch);
buffer.concat("(");
compileNode(param, state, "IdentifierName");
buffer.concat(")");
buffer.concatFormat(format.beforeCatchStatement);
}
else
{
buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("catch(");
buffer.concat(name);
buffer.concat(") ");
}
}
indentation += indentStep;
inner.skipIndentation = true;
compileNode(handler.body, inner, "ScopeBody");
indentation = indentation.substring(indentSize);
inner.copyAddedSelfToIvarsToParent();
}
if (node.finalizer)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeCatch);
buffer.concat("finally");
buffer.concatFormat(format.beforeCatchStatement);
}
else
{
buffer.concat("\n");
buffer.concat(indentation);
buffer.concat("finally ");
}
}
indentation += indentStep;
state.skipIndentation = true;
compileNode(node.finalizer, state, "Statement");
indentation = indentation.substring(indentSize);
}
if (generate && !format)
buffer.concat("\n");
},
WhileStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("while", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("while (", node);
}
}
compileNode(node.test, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
DoWhileStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("do", node);
buffer.concatFormat(format.beforeStatement);
}
else
{
buffer.concat(indentation);
buffer.concat("do\n", node);
}
}
indentation += indentStep;
compileNode(node.body, state, "Statement");
indentation = indentation.substring(indentSize);
if (generate)
{
if (format)
{
buffer.concat("while");
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("while (");
}
}
compileNode(node.test, state, "Expression");
if (generate)
buffer.concatFormat(format ? ")" : ");\n");
},
ForStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("for", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("for (", node);
}
}
if (node.init)
compileNode(node.init, state, "ForInit");
if (generate)
buffer.concat(format ? ";" : "; ");
if (node.test)
compileNode(node.test, state, "Expression");
if (generate)
buffer.concat(format ? ";" : "; ");
if (node.update)
compileNode(node.update, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
ForInStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
body = node.body,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concat("for", node);
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
}
else
{
buffer.concat(indentation);
buffer.concat("for (", node);
}
}
compileNode(node.left, state, "ForInit");
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeIn);
buffer.concat("in");
buffer.concatFormat(format.afterIn);
}
else
buffer.concat(" in ");
}
compileNode(node.right, state, "Expression");
if (generate)
{
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
{
// We don't want EmptyStatements to generate an extra parenthesis except when it is in a while, for, ...
buffer.concat(body.type === "EmptyStatement" ? ");\n" : ")\n");
}
}
indentation += indentStep;
compileNode(body, state, "Statement");
indentation = indentation.substring(indentSize);
},
ForInit: function(node, state, compileNode)
{
if (node.type === "VariableDeclaration")
{
state.isFor = true;
compileNode(node, state);
delete state.isFor;
}
else
compileNode(node, state, "Expression");
},
DebuggerStatement: function(node, state, compileNode, format)
{
var compiler = state.compiler;
if (compiler.generate)
{
var buffer = compiler.jsBuffer;
if (format)
buffer.concat("debugger", node);
else
{
buffer.concat(indentation);
buffer.concat("debugger;\n", node);
}
}
},
Function: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
inner = new Scope(state),
decl = node.type === "FunctionDeclaration",
id = node.id;
inner.isDecl = decl;
for (var i = 0; i < node.params.length; ++i)
inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]};
if (generate && !format)
buffer.concat(indentation);
if (id)
{
var name = id.name;
(decl ? state : inner).vars[name] = {type: decl ? "function" : "function name", node: id};
if (compiler.transformNamedFunctionToAssignment)
{
if (generate)
{
buffer.concat(name);
buffer.concat(" = ");
}
else
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(name);
buffer.concat(" = function");
compiler.lastPos = id.end;
}
}
}
if (generate)
{
buffer.concat("function", node);
if (!compiler.transformNamedFunctionToAssignment && id)
{
if (!format)
buffer.concat(" ");
compileNode(id, state, "IdentifierName");
}
if (format)
buffer.concatFormat(format.beforeLeftParenthesis);
buffer.concat("(");
for (i = 0; i < node.params.length; ++i)
{
if (i)
buffer.concat(format ? "," : ", ");
compileNode(node.params[i], state, "IdentifierName");
}
if (format)
{
buffer.concat(")");
buffer.concatFormat(format.afterRightParenthesis);
}
else
buffer.concat(")\n");
}
indentation += indentStep;
compileNode(node.body, inner, "ScopeBody");
indentation = indentation.substring(indentSize);
inner.copyAddedSelfToIvarsToParent();
},
VariableDeclaration: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer,
decl,
identifier;
if (generate)
{
buffer = compiler.jsBuffer;
if (!state.isFor && !format)
buffer.concat(indentation);
buffer.concat(format ? "var" : "var ", node);
}
for (var i = 0; i < node.declarations.length; ++i)
{
decl = node.declarations[i];
identifier = decl.id.name;
if (i)
{
if (generate)
{
if (format)
buffer.concat(",");
else
{
if (state.isFor)
buffer.concat(", ");
else
{
buffer.concat(",\n");
buffer.concat(indentation);
buffer.concat(" ");
}
}
}
}
state.vars[identifier] = {type: "var", node: decl.id};
compileNode(decl.id, state, "IdentifierName");
if (decl.init)
{
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeEqual);
buffer.concat("=");
buffer.concatFormat(format.afterEqual);
}
else
buffer.concat(" = ");
}
compileNode(decl.init, state, "Expression");
}
// FIXME: Extract to function
// Here we check back if a ivar with the same name exists and if we have prefixed 'self.' on previous uses.
// If this is the case we have to remove the prefixes and issue a warning that the variable hides the ivar.
if (state.addedSelfToIvars)
{
var addedSelfToIvar = state.addedSelfToIvars[identifier];
if (addedSelfToIvar)
{
var atoms = state.compiler.jsBuffer.atoms,
size = addedSelfToIvar.length;
for (i = 0; i < size; i++)
{
var dict = addedSelfToIvar[i];
atoms[dict.index] = "";
compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides instance variable", dict.node, compiler.source));
}
state.addedSelfToIvars[identifier] = [];
}
}
}
if (generate && !format && !state.isFor)
buffer.concat(";\n"); // Don't add ';' if this is a for statement but do it if this is a statement
},
ThisExpression: function(node, state)
{
var compiler = state.compiler;
if (compiler.generate)
compiler.jsBuffer.concat("this", node);
},
ArrayExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("[", node);
}
for (var i = 0; i < node.elements.length; ++i)
{
var elt = node.elements[i];
if (generate && i !== 0)
{
if (format)
{
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
}
else
buffer.concat(", ");
}
if (elt)
compileNode(elt, state, "Expression");
}
if (generate)
buffer.concat("]");
},
ObjectExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
properties = node.properties,
buffer = compiler.jsBuffer;
if (generate)
buffer.concat("{", node);
for (var i = 0, size = properties.length; i < size; ++i)
{
var prop = properties[i];
if (generate)
{
if (i)
{
if (format) {
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
} else
buffer.concat(", ");
}
state.isPropertyKey = true;
compileNode(prop.key, state, "Expression");
delete state.isPropertyKey;
if (format)
{
buffer.concatFormat(format.beforeColon);
buffer.concat(":");
buffer.concatFormat(format.afterColon);
}
else
buffer.concat(": ");
}
else if (prop.key.raw && prop.key.raw.charAt(0) === "@")
{
buffer.concat(compiler.source.substring(compiler.lastPos, prop.key.start));
compiler.lastPos = prop.key.start + 1;
}
compileNode(prop.value, state, "Expression");
}
if (generate)
buffer.concat("}");
},
SequenceExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("(");
}
for (var i = 0; i < node.expressions.length; ++i)
{
if (generate && i !== 0)
{
if (format)
{
buffer.concatFormat(format.beforeComma);
buffer.concat(",");
buffer.concatFormat(format.afterComma);
}
else
buffer.concat(", ");
}
compileNode(node.expressions[i], state, "Expression");
}
if (generate)
buffer.concat(")");
},
UnaryExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
argument = node.argument;
if (generate)
{
var buffer = compiler.jsBuffer;
if (node.prefix)
{
buffer.concat(node.operator, node);
if (wordPrefixOperators(node.operator))
buffer.concat(" ");
parenthesizeExpression(generate, node, argument, state, compileNode);
}
else
{
parenthesizeExpression(generate, node, argument, state, compileNode);
buffer.concat(node.operator);
}
}
else
compileNode(argument, state, "Expression");
},
UpdateExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer;
if (node.argument.type === "Dereference")
{
checkCanDereference(state, node.argument);
// @deref(x)++ and ++@deref(x) require special handling.
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Output the dereference function, "(...)(z)"
buffer.concat((node.prefix ? "" : "(") + "(");
// The thing being dereferenced.
if (!generate)
compiler.lastPos = node.argument.expr.start;
compileNode(node.argument.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.argument.expr.end));
buffer.concat(")(");
if (!generate)
compiler.lastPos = node.argument.start;
compileNode(node.argument, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.argument.end));
buffer.concat(" " + node.operator.substring(0, 1) + " 1)" + (node.prefix ? "" : (node.operator === "++" ? " - 1)" : " + 1)")));
if (!generate)
compiler.lastPos = node.end;
return;
}
if (node.prefix)
{
if (generate)
{
buffer.concat(node.operator, node);
if (wordPrefixOperators(node.operator))
buffer.concat(" ");
}
parenthesizeExpression(generate, node, node.argument, state, compileNode);
}
else
{
parenthesizeExpression(generate, node, node.argument, state, compileNode);
if (generate)
buffer.concat(node.operator);
}
},
BinaryExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
var buffer = compiler.jsBuffer;
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
},
LogicalExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
var buffer = compiler.jsBuffer;
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
},
AssignmentExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer;
if (node.left.type === "Dereference")
{
checkCanDereference(state, node.left);
// @deref(x) = z -> x(z) etc
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Output the dereference function, "(...)(z)"
buffer.concat("(");
// What's being dereferenced could itself be an expression, such as when dereferencing a deref.
if (!generate)
compiler.lastPos = node.left.expr.start;
compileNode(node.left.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.left.expr.end));
buffer.concat(")(");
// Now "(x)(...)". We have to manually expand +=, -=, *= etc.
if (node.operator !== "=")
{
// Output the whole .left, not just .left.expr.
if (!generate)
compiler.lastPos = node.left.start;
compileNode(node.left, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.left.end));
buffer.concat(" " + node.operator.substring(0, 1) + " ");
}
if (!generate)
compiler.lastPos = node.right.start;
compileNode(node.right, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.right.end));
buffer.concat(")");
if (!generate)
compiler.lastPos = node.end;
}
else
{
var saveAssignment = state.assignment;
state.assignment = true;
parenthesizeExpression(generate, node, node.left, state, compileNode);
if (generate)
{
buffer.concatFormat(format ? format.beforeOperator : " ");
buffer.concat(node.operator);
buffer.concatFormat(format ? format.afterOperator : " ");
}
state.assignment = saveAssignment;
parenthesizeExpression(generate, node, node.right, state, compileNode, true);
if (state.isRootScope() && node.left.type === "Identifier" && !state.getLvar(node.left.name))
state.vars[node.left.name] = {type: "global", node: node.left};
}
},
ConditionalExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer;
parenthesizeExpression(generate, node, node.test, state, compileNode);
if (generate)
{
buffer = compiler.jsBuffer;
if (format)
{
buffer.concatFormat(format.beforeOperator);
buffer.concat("?");
buffer.concatFormat(format.afterOperator);
}
else
buffer.concat(" ? ");
}
compileNode(node.consequent, state, "Expression");
if (generate)
{
if (format)
{
buffer.concatFormat(format.beforeOperator);
buffer.concat(":");
buffer.concatFormat(format.afterOperator);
}
else
buffer.concat(" : ");
}
compileNode(node.alternate, state, "Expression");
},
NewExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
nodeArguments = node.arguments,
generate = compiler.generate,
buffer;
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("new ", node);
}
parenthesizeExpression(generate, node, node.callee, state, compileNode);
if (generate)
buffer.concat("(");
if (nodeArguments)
{
for (var i = 0, size = nodeArguments.length; i < size; ++i)
{
if (i > 0 && generate)
buffer.concatFormat(format ? "," : ", ");
compileNode(nodeArguments[i], state, "Expression");
}
}
if (generate)
buffer.concat(")");
},
CallExpression: function(node, state, compileNode, format)
{
var compiler = state.compiler,
nodeArguments = node.arguments,
generate = compiler.generate,
buffer;
parenthesizeExpression(generate, node, node.callee, state, compileNode);
if (generate)
{
buffer = compiler.jsBuffer;
buffer.concat("(");
}
if (nodeArguments)
{
for (var i = 0, size = nodeArguments.length; i < size; ++i)
{
if (i > 0 && generate)
buffer.concat(format ? "," : ", ");
compileNode(nodeArguments[i], state, "Expression");
}
}
if (generate)
buffer.concat(")");
},
MemberExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
computed = node.computed;
parenthesizeExpression(generate, node, node.object, state, compileNode);
if (generate)
compiler.jsBuffer.concat(computed ? "[" : ".", node);
state.secondMemberExpression = !computed;
// No parentheses when it is computed, '[' amd ']' are the same thing.
parenthesizeExpression(generate && !computed, node, node.property, state, compileNode);
state.secondMemberExpression = false;
if (generate && computed)
compiler.jsBuffer.concat("]");
},
Identifier: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate,
identifier = node.name;
if (state.currentMethodType() === "-" && !state.secondMemberExpression && !state.isPropertyKey)
{
var lvar = state.getLvar(identifier, true), // Only look inside method
ivar = compiler.getIvarForClass(identifier, state);
if (ivar)
{
if (lvar)
compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides instance variable", node, compiler.source));
else
{
var nodeStart = node.start;
if (!generate)
{
do
{
// The Spider Monkey AST tree includes any parentheses in start and end properties
// so we have to make sure we skip those
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, nodeStart));
compiler.lastPos = nodeStart;
}
while (compiler.source.substr(nodeStart++, 1) === "(");
}
// Save the index of where the "self." string is stored and the node.
// These will be used if we find a variable declaration that is hoisting this identifier.
((state.addedSelfToIvars || (state.addedSelfToIvars = Object.create(null)))[identifier] || (state.addedSelfToIvars[identifier] = [])).push({node: node, index: compiler.jsBuffer.length()});
compiler.jsBuffer.concat("self.", node);
}
}
// Don't check for warnings if it is a reserved word like self, localStorage, _cmd, etc...
else if (!reservedIdentifiers(identifier))
{
var message,
classOrGlobal = typeof global[identifier] !== "undefined" || (typeof window !== "undefined" && typeof window[identifier] !== "undefined") || compiler.getClassDef(identifier),
globalVar = state.getLvar(identifier);
// It can't be declared with a @class statement
if (classOrGlobal && (!globalVar || globalVar.type !== "class"))
{
/* jshint -W035 */
/* Turned off this warning as there are many many warnings when compiling the Cappuccino frameworks - Martin
if (lvar) {
message = compiler.addWarning(createMessage("Local declaration of '" + identifier + "' hides global variable", node, compiler.source));
}*/
}
else if (!globalVar)
{
if (state.assignment)
{
message = new GlobalVariableMaybeWarning("Creating global variable inside function or method '" + identifier + "'", node, compiler.source);
// Turn off these warnings for this identifier, we only want one.
state.vars[identifier] = {type: "remove global warning", node: node};
}
else
{
message = new GlobalVariableMaybeWarning("Using unknown class or uninitialized global variable '" + identifier + "'", node, compiler.source);
}
}
if (message)
state.addMaybeWarning(message);
}
}
if (generate)
compiler.jsBuffer.concat(identifier, node);
},
// Use this when there should not be a look up to issue warnings or add 'self.' before ivars
IdentifierName: function(node, state)
{
var compiler = state.compiler;
if (compiler.generate)
compiler.jsBuffer.concat(node.name, node);
},
Literal: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate;
if (generate)
{
if (node.raw && node.raw.charAt(0) === "@")
compiler.jsBuffer.concat(node.raw.substring(1), node);
else
compiler.jsBuffer.concat(node.raw, node);
}
else if (node.raw.charAt(0) === "@")
{
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start + 1;
}
},
ArrayLiteral: function(node, state, compileNode)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ,
elementLength = node.elements.length;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
}
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("@[");
else if (!elementLength)
buffer.concat("objj_msgSend(objj_msgSend(CPArray, \"alloc\"), \"init\")", node);
else
buffer.concat("objj_msgSend(objj_msgSend(CPArray, \"alloc\"), \"initWithObjects:count:\", [", node);
if (elementLength)
{
for (var i = 0; i < elementLength; i++)
{
var elt = node.elements[i];
if (i)
buffer.concat(", ");
if (!generate)
compiler.lastPos = elt.start;
compileNode(elt, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, elt.end));
}
if (!generateObjJ)
buffer.concat("], " + elementLength + ")");
}
if (generateObjJ)
buffer.concat("]");
if (!generate)
compiler.lastPos = node.end;
},
DictionaryLiteral: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ,
keyLength = node.keys.length;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
}
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
{
buffer.concat("@{");
for (var i = 0; i < keyLength; i++)
{
if (i !== 0)
buffer.concat(",");
compileNode(node.keys[i], state, "Expression");
buffer.concat(":");
compileNode(node.values[i], state, "Expression");
}
buffer.concat("}");
}
else if (!keyLength)
{
buffer.concat("objj_msgSend(objj_msgSend(CPDictionary, \"alloc\"), \"init\")", node);
}
else
{
buffer.concat("objj_msgSend(objj_msgSend(CPDictionary, \"alloc\"), \"initWithObjectsAndKeys:\"", node);
for (var i = 0; i < keyLength; i++)
{
var key = node.keys[i],
value = node.values[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = value.start;
compileNode(value, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, value.end));
buffer.concat(", ");
if (!generate)
compiler.lastPos = key.start;
compileNode(key, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, key.end));
}
buffer.concat(")");
}
if (!generate)
compiler.lastPos = node.end;
},
ImportStatement: function(node, state)
{
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
isLocal = node.isLocal,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
if (generateObjJ)
{
buffer.concat("@import ");
buffer.concat(isLocal ? "\"" : "<");
buffer.concat(node.filename.value);
buffer.concat(isLocal ? "\"" : ">");
}
else
{
buffer.concat("objj_executeFile(\"", node);
buffer.concat(node.filename.value);
buffer.concat(isLocal ? "\", YES);" : "\", NO);");
}
if (!generate)
compiler.lastPos = node.end;
},
ClassDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
saveJSBuffer = compiler.jsBuffer,
className = node.classname.name,
classDef = compiler.getClassDef(className),
classScope = new Scope(state),
isInterfaceDeclaration = node.type === "InterfaceDeclarationStatement",
protocols = node.protocols,
generateObjJ = compiler.options.generateObjJ;
compiler.imBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
compiler.cmBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
// TODO: Check if this is needed
compiler.classBodyBuffer = new StringBuffer(compiler.createSourceMap, compiler.URL);
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// First we declare the class
classDef = declareClass(compiler, node, classDef, className, isInterfaceDeclaration, generateObjJ, saveJSBuffer);
if (generateObjJ)
{
saveJSBuffer.concat(isInterfaceDeclaration ? "@interface " : "@implementation ");
saveJSBuffer.concat(className);
if (node.superclassname)
{
saveJSBuffer.concat(" : ");
compileNode(node.superclassname, state, "IdentifierName");
}
else if (node.categoryname)
{
saveJSBuffer.concat(" (");
compileNode(node.categoryname, state, "IdentifierName");
saveJSBuffer.concat(")");
}
}
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
{
if (generateObjJ) {
if (i)
saveJSBuffer.concat(", ");
else
saveJSBuffer.concat(" <");
compileNode(protocols[i], state, "IdentifierName");
if (i === size - 1)
saveJSBuffer.concat(">");
} else {
saveJSBuffer.concat("\nvar aProtocol = objj_getProtocol(\"" + protocols[i].name + "\");", protocols[i]);
saveJSBuffer.concat("\nif (!aProtocol) throw new SyntaxError(\"*** Could not find definition for protocol \\\"" + protocols[i].name + "\\\"\");");
saveJSBuffer.concat("\nclass_addProtocol(the_class, aProtocol);");
}
}
}
classScope.classDef = classDef;
compiler.currentSuperClass = "objj_getClass(\"" + className + "\").super_class";
compiler.currentSuperMetaClass = "objj_getMetaClass(\"" + className + "\").super_class";
var firstIvarDeclaration = true,
hasAccessors = false;
// Now we add all ivars
if (node.ivardeclarations)
hasAccessors = addIvars(compiler, node, compileNode, state, classDef, className, classScope, firstIvarDeclaration, generateObjJ, saveJSBuffer);
if (generateObjJ)
{
indentation = indentation.substring(indentSize);
saveJSBuffer.concatFormat("\n}");
}
else if (!firstIvarDeclaration)
saveJSBuffer.concat("]);");
// If we have accessors add get and set methods for them
if (!generateObjJ && !isInterfaceDeclaration && hasAccessors)
generateGetterSetter(compiler, node);
// We will store the classDef first after accessors are done so we don't get a duplicate class error
compiler.classDefs[className] = classDef;
var bodies = node.body,
bodyLength = bodies.length;
if (bodyLength > 0)
{
var body;
if (!generate)
compiler.lastPos = bodies[0].start;
// And last add methods and other statements
for (var i = 0; i < bodyLength; ++i)
{
body = bodies[i];
compileNode(body, classScope, "Statement");
}
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, body.end));
}
// We must make a new class object for our class definition if it's not a category
if (!generateObjJ && !isInterfaceDeclaration && !node.categoryname)
saveJSBuffer.concat("objj_registerClassPair(the_class);\n");
// Add instance methods
if (!generateObjJ && compiler.imBuffer.isEmpty())
{
saveJSBuffer.concat("class_addMethods(the_class, [");
saveJSBuffer.appendStringBuffer(compiler.imBuffer);
saveJSBuffer.concat("]);\n");
}
// Add class methods
if (!generateObjJ && compiler.cmBuffer.isEmpty())
{
saveJSBuffer.concat("class_addMethods(meta_class, [");
saveJSBuffer.appendStringBuffer(compiler.cmBuffer);
saveJSBuffer.concat("]);\n");
}
if (!generateObjJ)
saveJSBuffer.concat("}");
compiler.jsBuffer = saveJSBuffer;
// Skip the "@end"
if (!generate)
compiler.lastPos = node.end;
if (generateObjJ)
saveJSBuffer.concat("\n@end");
// If the class conforms to protocols check that all required methods are implemented
if (protocols)
checkProtocolConformance(compiler, node, classDef, protocols);
},
ProtocolDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
protocolName = node.protocolname.name,
protocolDef = compiler.getProtocolDef(protocolName),
protocols = node.protocols,
protocolScope = new Scope(state),
inheritFromProtocols = [],
generateObjJ = compiler.options.generateObjJ;
if (protocolDef)
throw compiler.syntaxError("Duplicate protocol " + protocolName, node.protocolname);
compiler.imBuffer = new StringBuffer();
compiler.cmBuffer = new StringBuffer();
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
if (generateObjJ)
{
buffer.concat("@protocol ");
compileNode(node.protocolname, state, "IdentifierName");
}
else
buffer.concat("{var the_protocol = objj_allocateProtocol(\"" + protocolName + "\");", node);
if (protocols)
{
if (generateObjJ)
buffer.concat(" <");
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i],
inheritFromProtocolName = protocol.name,
inheritProtocolDef = compiler.getProtocolDef(inheritFromProtocolName);
if (!inheritProtocolDef)
throw compiler.syntaxError("Can't find protocol " + inheritFromProtocolName, protocol);
if (generateObjJ)
{
if (i)
buffer.concat(", ");
compileNode(protocol, state, "IdentifierName");
}
else
{
buffer.concat("\nvar aProtocol = objj_getProtocol(\"" + inheritFromProtocolName + "\");", node);
buffer.concat("\nif (!aProtocol) throw new SyntaxError(\"*** Could not find definition for protocol \\\"" + protocolName + "\\\"\");", node);
buffer.concat("\nprotocol_addProtocol(the_protocol, aProtocol);", node);
}
inheritFromProtocols.push(inheritProtocolDef);
}
if (generateObjJ)
buffer.concat(">");
}
protocolDef = new ProtocolDef(protocolName, inheritFromProtocols);
compiler.protocolDefs[protocolName] = protocolDef;
protocolScope.protocolDef = protocolDef;
var someRequired = node.required;
if (someRequired)
{
var requiredLength = someRequired.length;
if (requiredLength > 0)
{
var required;
// We only add the required methods
for (var i = 0; i < requiredLength; ++i)
{
required = someRequired[i];
if (!generate)
compiler.lastPos = required.start;
compileNode(required, protocolScope, "Statement");
}
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, required.end));
}
}
if (generateObjJ)
buffer.concatFormat("\n@end");
else
{
buffer.concat("\nobjj_registerProtocol(the_protocol);\n");
// Add instance methods
if (compiler.imBuffer.isEmpty())
{
buffer.concat("protocol_addMethodDescriptions(the_protocol, [");
buffer.atoms.push.apply(buffer.atoms, compiler.imBuffer.atoms); // FIXME: Move this append to StringBuffer
buffer.concat("], true, true);\n");
}
// Add class methods
if (compiler.cmBuffer.isEmpty())
{
buffer.concat("protocol_addMethodDescriptions(the_protocol, [");
buffer.atoms.push.apply(buffer.atoms, compiler.cmBuffer.atoms); // FIXME: Move this append to StringBuffer
buffer.concat("], true, false);\n");
}
buffer.concat("}");
}
compiler.jsBuffer = buffer;
// Skip @end
if (!generate)
compiler.lastPos = node.end;
},
IvarDeclaration: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer;
if (node.outlet)
buffer.concat("@outlet ");
compileNode(node.ivartype, state, "IdentifierName");
buffer.concat(" ");
compileNode(node.id, state, "IdentifierName");
if (node.accessors)
buffer.concat(" @accessors");
},
MethodDeclarationStatement: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
saveJSBuffer = compiler.jsBuffer,
methodScope = new Scope(state),
isInstanceMethodType = node.methodtype === "-",
selectors = node.selectors,
nodeArguments = node.arguments,
returnType = node.returntype,
// Return type is 'id' as default except if it is an action declared method, then it's 'void'
types = [returnType ? returnType.name : (node.action ? "void" : "id")],
returnTypeProtocols = returnType ? returnType.protocols : null,
selector = selectors[0].name, // There is always at least one selector
generateObjJ = compiler.options.generateObjJ;
if (returnTypeProtocols)
{
for (var i = 0, count = returnTypeProtocols.length; i < count; i++)
{
var returnTypeProtocol = returnTypeProtocols[i];
if (!compiler.getProtocolDef(returnTypeProtocol.name))
compiler.addWarning(createMessage("Cannot find protocol declaration for '" + returnTypeProtocol.name + "'", returnTypeProtocol, compiler.source));
}
}
if (!generate)
saveJSBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// If we are generating objective-J code write everything directly to the regular buffer
// Otherwise we have one for instance methods and one for class methods.
if (generateObjJ)
{
compiler.jsBuffer.concat(isInstanceMethodType ? "- (" : "+ (");
compiler.jsBuffer.concat(types[0]);
compiler.jsBuffer.concat(")");
}
else
compiler.jsBuffer = isInstanceMethodType ? compiler.imBuffer : compiler.cmBuffer;
// Put together the selector. Maybe this should be done in the parser...
// Or maybe we should do it here as when genereting Objective-J code it's kind of handy
if (nodeArguments.length > 0)
{
for (var i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i],
argumentType = argument.type,
argumentTypeName = argumentType ? argumentType.name : "id",
argumentProtocols = argumentType ? argumentType.protocols : null;
types.push(argumentTypeName);
if (i === 0)
selector += ":";
else
selector += (selectors[i] ? selectors[i].name : "") + ":";
if (argumentProtocols)
{
for (var j = 0, size = argumentProtocols.length; j < size; j++)
{
var argumentProtocol = argumentProtocols[j];
if (!compiler.getProtocolDef(argumentProtocol.name))
compiler.addWarning(createMessage("Cannot find protocol declaration for '" + argumentProtocol.name + "'", argumentProtocol, compiler.source));
}
}
if (generateObjJ)
{
var aSelector = selectors[i];
if (i)
compiler.jsBuffer.concat(" ");
compiler.jsBuffer.concat((aSelector ? aSelector.name : "") + ":");
compiler.jsBuffer.concat("(");
compiler.jsBuffer.concat(argumentTypeName);
if (argumentProtocols)
{
compiler.jsBuffer.concat(" <");
for (var j = 0, size = argumentProtocols.length; j < size; j++)
{
var argumentProtocol = argumentProtocols[j];
if (j)
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat(argumentProtocol.name);
}
compiler.jsBuffer.concat(">");
}
compiler.jsBuffer.concat(")");
compileNode(argument.identifier, state, "IdentifierName");
}
}
}
else if (generateObjJ)
{
var selector = selectors[0];
compiler.jsBuffer.concat(selector.name, selector);
}
if (generateObjJ)
{
if (node.parameters)
compiler.jsBuffer.concat(", ...");
}
else
{
if (compiler.jsBuffer.isEmpty()) // Add comma separator if this is not first method in this buffer
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat("new objj_method(sel_getUid(\"", node);
compiler.jsBuffer.concat(selector);
compiler.jsBuffer.concat("\"), ");
}
if (node.body)
{
if (!generateObjJ)
{
compiler.jsBuffer.concat("function");
if (compiler.options.generateMethodFunctionNames)
compiler.jsBuffer.concat(" $" + state.currentClassName() + "__" + selector.replace(/:/g, "_"));
compiler.jsBuffer.concat("(self, _cmd");
}
methodScope.methodType = node.methodtype;
if (nodeArguments)
{
for (var i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i],
argumentName = argument.identifier.name;
if (!generateObjJ)
{
compiler.jsBuffer.concat(", ");
compiler.jsBuffer.concat(argumentName, argument.identifier);
}
methodScope.vars[argumentName] = {type: "method argument", node: argument};
}
}
if (!generateObjJ)
compiler.jsBuffer.concat(")\n");
if (!generate)
compiler.lastPos = node.startOfBody;
indentation += indentStep;
compileNode(node.body, methodScope, "Statement");
indentation = indentation.substring(indentSize);
if (!generate)
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.body.end));
if (!generateObjJ)
compiler.jsBuffer.concat("\n");
}
else // It is a interface or protocol declaration and we don't have a method implementation
{
if (generateObjJ)
compiler.jsBuffer.concat(";");
else
compiler.jsBuffer.concat("Nil\n");
}
if (!generateObjJ)
{
if (compiler.options.generateMethodArgumentTypeSignatures)
compiler.jsBuffer.concat(","+JSON.stringify(types));
compiler.jsBuffer.concat(")");
compiler.jsBuffer = saveJSBuffer;
}
if (!generate)
compiler.lastPos = node.end;
// Add the method to the class or protocol definition
var def = state.classDef,
alreadyDeclared;
// But first, if it is a class definition check if it is declared in the superclass or interface declaration
if (def)
alreadyDeclared = isInstanceMethodType ? def.getInstanceMethod(selector) : def.getClassMethod(selector);
else
def = state.protocolDef;
if (!def)
throw "Internal error: MethodDeclaration without ClassDeclaration or ProtocolDeclaration at line: " + exports.acorn.getLineInfo(compiler.source, node.start).line;
// Create warnings if types do not correspond to the method declaration in the superclass or interface declarations.
// If we don't find the method in the superclass or interface declarations above or if it is a protocol
// declaration, try to find it in any of the conforming protocols.
if (!alreadyDeclared)
{
var protocols = def.protocols;
if (protocols)
{
for (var i = 0, size = protocols.length; i < size; i++)
{
var protocol = protocols[i],
alreadyDeclared = isInstanceMethodType ? protocol.getInstanceMethod(selector) : protocol.getClassMethod(selector);
if (alreadyDeclared)
break;
}
}
}
if (alreadyDeclared)
{
var declaredTypes = alreadyDeclared.types;
if (declaredTypes)
{
var typeSize = declaredTypes.length;
if (typeSize > 0)
{
// First type is return type
var declaredReturnType = declaredTypes[0];
// Create warning if return types are not the same.
// It is ok if superclass has 'id' and subclass has a class type.
if (declaredReturnType !== types[0] && !(declaredReturnType === "id" && returnType && returnType.typeisclass))
compiler.addWarning(createMessage("Conflicting return type in implementation of '" + selector + "': '" + declaredReturnType + "' vs '" + types[0] + "'", returnType || node.action || selectors[0], compiler.source));
// Check the parameter types. The size of the two type arrays
// should be the same as they have the same selector.
for (var i = 1; i < typeSize; i++)
{
var parameterType = declaredTypes[i];
if (parameterType !== types[i] && !(parameterType === "id" && nodeArguments[i - 1].type.typeisclass))
compiler.addWarning(createMessage("Conflicting parameter types in implementation of '" + selector + "': '" + parameterType + "' vs '" + types[i] + "'", nodeArguments[i - 1].type || nodeArguments[i - 1].identifier, compiler.source));
}
}
}
}
// Now we add it
var methodDef = new MethodDef(selector, types);
if (isInstanceMethodType)
def.addInstanceMethod(methodDef);
else
def.addClassMethod(methodDef);
},
MessageSendExpression: function(node, state, compileNode)
{
/* jshint -W004 */
var compiler = state.compiler,
generate = compiler.generate,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.object ? node.object.start : (node.arguments.length ? node.arguments[0].start : node.end);
}
if (node.superObject)
{
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("[super ");
else
{
buffer.concat("objj_msgSendSuper(", node);
buffer.concat("{ receiver:self, super_class:" + (state.currentMethodType() === "+" ? compiler.currentSuperMetaClass : compiler.currentSuperClass ) + " }");
}
}
else
{
// Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
if (!generate)
buffer.concat(" ");
if (generateObjJ)
buffer.concat("[", node);
else
buffer.concat("objj_msgSend(", node);
compileNode(node.object, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.object.end));
}
var selectors = node.selectors,
nodeArguments = node.arguments,
firstSelector = selectors[0],
// There is always at least one selector
selector = firstSelector ? firstSelector.name : "",
parameters = node.parameters;
if (generateObjJ)
{
for (var i = 0, size = nodeArguments.length; i < size || (size === 0 && i === 0); i++)
{
var sel = selectors[i];
buffer.concat(" ");
buffer.concat(sel ? sel.name : "");
if (size > 0)
{
var argument = nodeArguments[i];
buffer.concat(":");
compileNode(argument, state, "Expression");
}
}
if (parameters)
{
for (i = 0, size = parameters.length; i < size; ++i)
{
var parameter = parameters[i];
buffer.concat(", ");
compileNode(parameter, state, "Expression");
}
}
buffer.concat("]");
}
else
{
// Put together the selector. Maybe this should be done in the parser...
for (var i = 0; i < nodeArguments.length; i++)
{
if (i === 0)
selector += ":";
else
selector += (selectors[i] ? selectors[i].name : "") + ":";
}
buffer.concat(", \"");
buffer.concat(selector); // FIXME: sel_getUid(selector + "") ? This FIXME is from the old preprocessor compiler
buffer.concat("\"");
if (nodeArguments)
{
for (i = 0; i < nodeArguments.length; i++)
{
var argument = nodeArguments[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = argument.start;
compileNode(argument, state, "Expression");
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, argument.end));
compiler.lastPos = argument.end;
}
}
}
if (parameters)
{
for (i = 0; i < parameters.length; ++i)
{
var parameter = parameters[i];
buffer.concat(", ");
if (!generate)
compiler.lastPos = parameter.start;
compileNode(parameter, state, "Expression");
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, parameter.end));
compiler.lastPos = parameter.end;
}
}
}
buffer.concat(")");
}
if (!generate)
compiler.lastPos = node.end;
},
SelectorLiteralExpression: function(node, state)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
// Add an extra space if it looks something like this: "return(@selector(a:))". No space between return and expression.
buffer.concat(" ");
}
buffer.concat(generateObjJ ? "@selector(" : "sel_getUid(\"", node);
buffer.concat(node.selector);
buffer.concat(generateObjJ ? ")" : "\")");
if (!generate)
compiler.lastPos = node.end;
},
ProtocolLiteralExpression: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(" "); // Add an extra space if it looks something like this: "return(@protocol(a))". No space between return and expression.
}
buffer.concat(generateObjJ ? "@protocol(" : "objj_getProtocol(\"", node);
compileNode(node.id, state, "IdentifierName");
buffer.concat(generateObjJ ? ")" : "\")");
if (!generate)
compiler.lastPos = node.end;
},
Reference: function(node, state)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
buffer.concat(" "); // Add an extra space if it looks something like this: "return(<expression>)". No space between return and expression.
}
if (generateObjJ)
{
buffer.concat("@ref(", node);
buffer.concat(node.element.name, node.element);
buffer.concat(")", node);
}
else
{
buffer.concat("function(__input) { if (arguments.length) return ", node);
buffer.concat(node.element.name);
buffer.concat(" = __input; return ");
buffer.concat(node.element.name);
buffer.concat("; }");
}
if (!generate)
compiler.lastPos = node.end;
},
Dereference: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generate = compiler.generate,
generateObjJ = compiler.options.generateObjJ;
checkCanDereference(state, node.expr);
// @deref(y) -> y()
// @deref(@deref(y)) -> y()()
if (!generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.expr.start;
}
if (generateObjJ)
buffer.concat("@deref(");
compileNode(node.expr, state, "Expression");
if (!generate)
buffer.concat(compiler.source.substring(compiler.lastPos, node.expr.end));
if (generateObjJ)
buffer.concat(")");
else
buffer.concat("()");
if (!generate)
compiler.lastPos = node.end;
},
ClassStatement: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!compiler.generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
buffer.concat("//");
}
if (generateObjJ)
{
buffer.concat("@class ");
compileNode(node.id, state, "IdentifierName");
}
var className = node.id.name;
if (!compiler.getClassDef(className))
compiler.classDefs[className] = new ClassDef(false, className);
state.vars[node.id.name] = {type: "class", node: node.id};
},
GlobalStatement: function(node, state, compileNode)
{
var compiler = state.compiler,
buffer = compiler.jsBuffer,
generateObjJ = compiler.options.generateObjJ;
if (!compiler.generate)
{
buffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
buffer.concat("//");
}
if (generateObjJ)
{
buffer.concat("@global ");
compileNode(node.id, state, "IdentifierName");
}
state.rootScope().vars[node.id.name] = {type: "global", node: node.id};
},
PreprocessStatement: function(node, state)
{
var compiler = state.compiler;
if (!compiler.generate)
{
compiler.jsBuffer.concat(compiler.source.substring(compiler.lastPos, node.start));
compiler.lastPos = node.start;
compiler.jsBuffer.concat("//");
}
}
}); // var codeGenerator = walk.make()
}); // function wrapper
| Be consistent with ++, formatting.
| lib/compiler.js | Be consistent with ++, formatting. | <ide><path>ib/compiler.js
<ide> return true;
<ide>
<ide> case "ArrayExpression":
<del> for (var i = 0; i < node.elements.length; ++i)
<add> for (var i = 0; i < node.elements.length; i++)
<ide> {
<ide> if (!isIdempotentExpression(node.elements[i]))
<ide> return false;
<ide> return true;
<ide>
<ide> case "DictionaryLiteral":
<del> for (var i = 0; i < node.keys.length; ++i)
<add> for (var i = 0; i < node.keys.length; i++)
<ide> {
<ide> if (!isIdempotentExpression(node.keys[i]))
<ide> return false;
<ide> return true;
<ide>
<ide> case "ObjectExpression":
<del> for (var i = 0; i < node.properties.length; ++i)
<add> for (var i = 0; i < node.properties.length; i++)
<ide> if (!isIdempotentExpression(node.properties[i].value))
<ide> return false;
<ide>
<ide> return true;
<ide>
<ide> case "FunctionExpression":
<del> for (var i = 0; i < node.params.length; ++i)
<add> for (var i = 0; i < node.params.length; i++)
<ide> if (!isIdempotentExpression(node.params[i]))
<ide> return false;
<ide>
<ide> return true;
<ide>
<ide> case "SequenceExpression":
<del> for (var i = 0; i < node.expressions.length; ++i)
<add> for (var i = 0; i < node.expressions.length; i++)
<ide> if (!isIdempotentExpression(node.expressions[i]))
<ide> return false;
<ide>
<ide> indentStep = new Array(indentWidth + 1).join(indentString);
<ide> indentation = "";
<ide>
<del> for (var i = 0; i < node.body.length; ++i)
<add> for (var i = 0; i < node.body.length; i++)
<ide> compileNode(node.body[i], state, "Statement");
<ide>
<ide> if (!compiler.generate)
<ide> }
<ide> }
<ide>
<del> for (var i = 0; i < node.body.length; ++i)
<add> for (var i = 0; i < node.body.length; i++)
<ide> compileNode(node.body[i], state, "Statement");
<ide>
<ide> if (compiler.generate)
<ide>
<ide> indentation += indentStep;
<ide>
<del> for (var i = 0; i < node.cases.length; ++i)
<add> for (var i = 0; i < node.cases.length; i++)
<ide> {
<ide> var cs = node.cases[i];
<ide>
<ide>
<ide> indentation += indentStep;
<ide>
<del> for (var j = 0; j < cs.consequent.length; ++j)
<add> for (var j = 0; j < cs.consequent.length; j++)
<ide> compileNode(cs.consequent[j], state, "Statement");
<ide>
<ide> indentation = indentation.substring(indentSize);
<ide>
<ide> inner.isDecl = decl;
<ide>
<del> for (var i = 0; i < node.params.length; ++i)
<add> for (var i = 0; i < node.params.length; i++)
<ide> inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]};
<ide>
<ide> if (generate && !format)
<ide>
<ide> buffer.concat("(");
<ide>
<del> for (i = 0; i < node.params.length; ++i)
<add> for (i = 0; i < node.params.length; i++)
<ide> {
<ide> if (i)
<ide> buffer.concat(format ? "," : ", ");
<ide> buffer.concat(format ? "var" : "var ", node);
<ide> }
<ide>
<del> for (var i = 0; i < node.declarations.length; ++i)
<add> for (var i = 0; i < node.declarations.length; i++)
<ide> {
<ide> decl = node.declarations[i];
<ide> identifier = decl.id.name;
<ide> buffer.concat("[", node);
<ide> }
<ide>
<del> for (var i = 0; i < node.elements.length; ++i)
<add> for (var i = 0; i < node.elements.length; i++)
<ide> {
<ide> var elt = node.elements[i];
<ide>
<ide> if (generate)
<ide> buffer.concat("{", node);
<ide>
<del> for (var i = 0, size = properties.length; i < size; ++i)
<add> for (var i = 0, size = properties.length; i < size; i++)
<ide> {
<ide> var prop = properties[i];
<ide>
<ide> {
<ide> if (i)
<ide> {
<del> if (format) {
<add> if (format)
<add> {
<ide> buffer.concatFormat(format.beforeComma);
<ide> buffer.concat(",");
<ide> buffer.concatFormat(format.afterComma);
<del> } else
<add> }
<add> else
<ide> buffer.concat(", ");
<ide> }
<ide>
<ide> buffer.concat("(");
<ide> }
<ide>
<del> for (var i = 0; i < node.expressions.length; ++i)
<add> for (var i = 0; i < node.expressions.length; i++)
<ide> {
<ide> if (generate && i !== 0)
<ide> {
<ide>
<ide> if (nodeArguments)
<ide> {
<del> for (var i = 0, size = nodeArguments.length; i < size; ++i)
<add> for (var i = 0, size = nodeArguments.length; i < size; i++)
<ide> {
<ide> if (i > 0 && generate)
<ide> buffer.concatFormat(format ? "," : ", ");
<ide>
<ide> if (nodeArguments)
<ide> {
<del> for (var i = 0, size = nodeArguments.length; i < size; ++i)
<add> for (var i = 0, size = nodeArguments.length; i < size; i++)
<ide> {
<ide> if (i > 0 && generate)
<ide> buffer.concat(format ? "," : ", ");
<ide> {
<ide> for (var i = 0, size = protocols.length; i < size; i++)
<ide> {
<del> if (generateObjJ) {
<add> if (generateObjJ)
<add> {
<ide> if (i)
<ide> saveJSBuffer.concat(", ");
<ide> else
<ide> saveJSBuffer.concat(" <");
<add>
<ide> compileNode(protocols[i], state, "IdentifierName");
<add>
<ide> if (i === size - 1)
<ide> saveJSBuffer.concat(">");
<del> } else {
<add> }
<add> else
<add> {
<ide> saveJSBuffer.concat("\nvar aProtocol = objj_getProtocol(\"" + protocols[i].name + "\");", protocols[i]);
<ide> saveJSBuffer.concat("\nif (!aProtocol) throw new SyntaxError(\"*** Could not find definition for protocol \\\"" + protocols[i].name + "\\\"\");");
<ide> saveJSBuffer.concat("\nclass_addProtocol(the_class, aProtocol);");
<ide> compiler.lastPos = bodies[0].start;
<ide>
<ide> // And last add methods and other statements
<del> for (var i = 0; i < bodyLength; ++i)
<add> for (var i = 0; i < bodyLength; i++)
<ide> {
<ide> body = bodies[i];
<ide> compileNode(body, classScope, "Statement");
<ide> var required;
<ide>
<ide> // We only add the required methods
<del> for (var i = 0; i < requiredLength; ++i)
<add> for (var i = 0; i < requiredLength; i++)
<ide> {
<ide> required = someRequired[i];
<ide>
<ide>
<ide> if (parameters)
<ide> {
<del> for (i = 0, size = parameters.length; i < size; ++i)
<add> for (i = 0, size = parameters.length; i < size; i++)
<ide> {
<ide> var parameter = parameters[i];
<ide> buffer.concat(", ");
<ide>
<ide> if (parameters)
<ide> {
<del> for (i = 0; i < parameters.length; ++i)
<add> for (i = 0; i < parameters.length; i++)
<ide> {
<ide> var parameter = parameters[i];
<ide> buffer.concat(", "); |
|
Java | apache-2.0 | edd07ec762b4f786ddae260f3731137cef469536 | 0 | rfh2000/UDA_Friendly_Chat | /**
* Copyright Google Inc. All Rights Reserved.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.udacity.friendlychat;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
// Request code value
public static final int RC_SIGN_IN = 123;
private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
// Initalize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
// Initialize references to views
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageListView = (ListView) findViewById(R.id.messageListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
// Initialize message ListView and its adapter
List<FriendlyMessage> friendlyMessages = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
mMessageListView.setAdapter(mMessageAdapter);
// Initialize progress bar
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: Fire an intent to show an image picker
}
});
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Send message to the db
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
mMessagesDatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// The getValue() method can take a class as a parameter, and the code will de-serialize the message
// This works because the messages object has the exact same field as the FriendlyMessage POJO
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlyMessage);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
// user is signed in
Toast.makeText(MainActivity.this, "You are now signed in", Toast.LENGTH_SHORT).show();
} else {
// user is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false) //SmartLock allows phone to auto-save the user's creds and try to log them in - disable for testing
.setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
protected void onPause() {
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
| app/src/main/java/com/google/firebase/udacity/friendlychat/MainActivity.java | /**
* Copyright Google Inc. All Rights Reserved.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.udacity.friendlychat;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
// Initalize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
// Initialize references to views
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageListView = (ListView) findViewById(R.id.messageListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
// Initialize message ListView and its adapter
List<FriendlyMessage> friendlyMessages = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
mMessageListView.setAdapter(mMessageAdapter);
// Initialize progress bar
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: Fire an intent to show an image picker
}
});
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Send message to the db
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
mMessagesDatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// The getValue() method can take a class as a parameter, and the code will de-serialize the message
// This works because the messages object has the exact same field as the FriendlyMessage POJO
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlyMessage);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
protected void onPause() {
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
| Actions for auth state changed
| app/src/main/java/com/google/firebase/udacity/friendlychat/MainActivity.java | Actions for auth state changed | <ide><path>pp/src/main/java/com/google/firebase/udacity/friendlychat/MainActivity.java
<ide> import android.widget.ImageButton;
<ide> import android.widget.ListView;
<ide> import android.widget.ProgressBar;
<del>
<add>import android.widget.Toast;
<add>
<add>import com.firebase.ui.auth.AuthUI;
<ide> import com.google.firebase.auth.FirebaseAuth;
<add>import com.google.firebase.auth.FirebaseUser;
<ide> import com.google.firebase.database.ChildEventListener;
<ide> import com.google.firebase.database.DataSnapshot;
<ide> import com.google.firebase.database.DatabaseError;
<ide> import com.google.firebase.database.FirebaseDatabase;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> public class MainActivity extends AppCompatActivity {
<ide>
<ide> public static final String ANONYMOUS = "anonymous";
<ide> public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
<add> // Request code value
<add> public static final int RC_SIGN_IN = 123;
<ide>
<ide> private ListView mMessageListView;
<ide> private MessageAdapter mMessageAdapter;
<ide> mAuthStateListener = new FirebaseAuth.AuthStateListener(){
<ide> @Override
<ide> public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
<del>
<add> FirebaseUser user = firebaseAuth.getCurrentUser();
<add> if (user != null){
<add> // user is signed in
<add> Toast.makeText(MainActivity.this, "You are now signed in", Toast.LENGTH_SHORT).show();
<add> } else {
<add> // user is signed out
<add> startActivityForResult(
<add> AuthUI.getInstance()
<add> .createSignInIntentBuilder()
<add> .setIsSmartLockEnabled(false) //SmartLock allows phone to auto-save the user's creds and try to log them in - disable for testing
<add> .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
<add> new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
<add> .build(),
<add> RC_SIGN_IN);
<add> }
<ide> }
<ide> };
<ide> } |
|
Java | apache-2.0 | 2c095347b5d409c54d3443b7e9f1c6dbbd761756 | 0 | apache/commons-compress,lookout/commons-compress,lookout/commons-compress,mohanaraosv/commons-compress,krosenvold/commons-compress,mohanaraosv/commons-compress,apache/commons-compress,krosenvold/commons-compress,apache/commons-compress,mohanaraosv/commons-compress,lookout/commons-compress,krosenvold/commons-compress | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URL;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;
public class Zip64SupportTest {
private static final long FIVE_BILLION = 5000000000l;
private static final int ONE_HUNDRED_THOUSAND = 100000;
@Test public void read5GBOfZerosUsingInputStream() throws Throwable {
FileInputStream fin = new FileInputStream(get5GBZerosFile());
ZipArchiveInputStream zin = null;
try {
zin = new ZipArchiveInputStream(fin);
ZipArchiveEntry zae = zin.getNextZipEntry();
assertEquals("5GB_of_Zeros", zae.getName());
assertEquals(FIVE_BILLION, zae.getSize());
byte[] buf = new byte[1024 * 1024];
long read = 0;
Random r = new Random(System.currentTimeMillis());
int readNow;
while ((readNow = zin.read(buf, 0, buf.length)) > 0) {
// testing all bytes for a value of 0 is going to take
// too long, just pick a few ones randomly
for (int i = 0; i < 1024; i++) {
int idx = r.nextInt(readNow);
assertEquals("testing byte " + (read + idx), 0, buf[idx]);
}
read += readNow;
}
assertEquals(FIVE_BILLION, read);
assertNull(zin.getNextZipEntry());
} finally {
if (zin != null) {
zin.close();
}
if (fin != null) {
fin.close();
}
}
}
@Test public void read100KFilesUsingInputStream() throws Throwable {
FileInputStream fin = new FileInputStream(get100KFileFile());
ZipArchiveInputStream zin = null;
try {
zin = new ZipArchiveInputStream(fin);
int files = 0;
ZipArchiveEntry zae = null;
while ((zae = zin.getNextZipEntry()) != null) {
if (!zae.isDirectory()) {
files++;
assertEquals(0, zae.getSize());
}
}
assertEquals(ONE_HUNDRED_THOUSAND, files);
} finally {
if (zin != null) {
zin.close();
}
fin.close();
}
}
@Test public void write100KFiles() throws Throwable {
withTemporaryArchive("write100KFiles", new ZipOutputTest() {
public void test(File f, ZipArchiveOutputStream zos)
throws IOException {
for (int i = 0; i < ONE_HUNDRED_THOUSAND; i++) {
ZipArchiveEntry zae =
new ZipArchiveEntry(String.valueOf(i));
zae.setSize(0);
zos.putArchiveEntry(zae);
zos.closeArchiveEntry();
}
zos.close();
RandomAccessFile a = new RandomAccessFile(f, "r");
try {
final long end = a.length();
// validate "end of central directory" is at
// the end of the file and contains the magic
// value 0xFFFF as "number of entries".
a.seek(end
- 22 /* length of EOCD without file comment */);
byte[] eocd = new byte[12];
a.readFully(eocd);
assertArrayEquals(new byte[] {
// sig
(byte) 0x50, (byte) 0x4b, 5, 6,
// disk numbers
0, 0, 0, 0,
// entries
(byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff,
}, eocd);
// validate "Zip64 end of central directory
// locator" is right in front of the EOCD and
// the location of the "Zip64 end of central
// directory record" seems correct
long expectedZ64EocdOffset = end - 22 /* eocd.length */
- 20 /* z64 eocd locator.length */
- 56 /* z64 eocd without extensible data sector */;
byte[] loc =
ZipEightByteInteger.getBytes(expectedZ64EocdOffset);
a.seek(end - 22 - 20);
byte[] z64EocdLoc = new byte[20];
a.readFully(z64EocdLoc);
assertArrayEquals(new byte[] {
// sig
(byte) 0x50, (byte) 0x4b, 6, 7,
// disk numbers
0, 0, 0, 0,
// location of Zip64 EOCD,
loc[0], loc[1], loc[2], loc[3],
loc[4], loc[5], loc[6], loc[7],
// total number of disks
1, 0, 0, 0,
}, z64EocdLoc);
// validate "Zip64 end of central directory
// record" is where it is supposed to be, the
// known values are fine and read the location
// of the central directory from it
a.seek(expectedZ64EocdOffset);
byte[] z64EocdStart = new byte[40];
a.readFully(z64EocdStart);
assertArrayEquals(new byte[] {
// sig
(byte) 0x50, (byte) 0x4b, 6, 6,
// size of z64 EOCD
44, 0, 0, 0,
0, 0, 0, 0,
// version made by
45, 0,
// version needed to extract
45, 0,
// disk numbers
0, 0, 0, 0,
0, 0, 0, 0,
// number of entries 100k = 0x186A0
(byte) 0xA0, (byte) 0x86, 1, 0,
0, 0, 0, 0,
(byte) 0xA0, (byte) 0x86, 1, 0,
0, 0, 0, 0,
}, z64EocdStart);
a.seek(expectedZ64EocdOffset + 48 /* skip size */);
byte[] cdOffset = new byte[8];
a.readFully(cdOffset);
long cdLoc = ZipEightByteInteger.getLongValue(cdOffset);
// finally verify there really is a central
// directory entry where the Zip64 EOCD claims
a.seek(cdLoc);
byte[] sig = new byte[4];
a.readFully(sig);
assertArrayEquals(new byte[] {
(byte) 0x50, (byte) 0x4b, 1, 2,
}, sig);
} finally {
a.close();
}
}
});
}
static interface ZipOutputTest {
void test(File f, ZipArchiveOutputStream zos) throws IOException;
}
private static void withTemporaryArchive(String testName,
ZipOutputTest test)
throws Throwable {
File f = getTempFile(testName);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(f);
try {
test.test(f, zos);
} catch (IOException ex) {
System.err.println("Failed to write archive because of: "
+ ex.getMessage()
+ " - likely not enough disk space.");
assumeTrue(false);
} finally {
zos.close();
}
}
private static File getFile(String name) throws Throwable {
URL url = Zip64SupportTest.class.getResource(name);
assumeNotNull(url);
File file = new File(new URI(url.toString()));
assumeTrue(file.exists());
return file;
}
private static File get5GBZerosFile() throws Throwable {
return getFile("/5GB_of_Zeros.zip");
}
private static File get100KFileFile() throws Throwable {
return getFile("/100k_Files.zip");
}
private static File getTempFile(String testName) throws Throwable {
File f = File.createTempFile("commons-compress-" + testName, ".zip");
f.deleteOnExit();
return f;
}
}
| src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URL;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;
public class Zip64SupportTest {
private static final long FIVE_BILLION = 5000000000l;
private static final int ONE_HUNDRED_THOUSAND = 100000;
@Test public void read5GBOfZerosUsingInputStream() throws Throwable {
FileInputStream fin = new FileInputStream(get5GBZerosFile());
ZipArchiveInputStream zin = null;
try {
zin = new ZipArchiveInputStream(fin);
ZipArchiveEntry zae = zin.getNextZipEntry();
assertEquals("5GB_of_Zeros", zae.getName());
assertEquals(FIVE_BILLION, zae.getSize());
byte[] buf = new byte[1024 * 1024];
long read = 0;
Random r = new Random(System.currentTimeMillis());
int readNow;
while ((readNow = zin.read(buf, 0, buf.length)) > 0) {
// testing all bytes for a value of 0 is going to take
// too long, just pick a few ones randomly
for (int i = 0; i < 1024; i++) {
int idx = r.nextInt(readNow);
assertEquals("testing byte " + (read + idx), 0, buf[idx]);
}
read += readNow;
}
assertEquals(FIVE_BILLION, read);
assertNull(zin.getNextZipEntry());
} finally {
if (zin != null) {
zin.close();
}
if (fin != null) {
fin.close();
}
}
}
@Test public void read100KFilesUsingInputStream() throws Throwable {
FileInputStream fin = new FileInputStream(get100KFileFile());
ZipArchiveInputStream zin = null;
try {
zin = new ZipArchiveInputStream(fin);
int files = 0;
ZipArchiveEntry zae = null;
while ((zae = zin.getNextZipEntry()) != null) {
if (!zae.isDirectory()) {
files++;
assertEquals(0, zae.getSize());
}
}
assertEquals(ONE_HUNDRED_THOUSAND, files);
} finally {
if (zin != null) {
zin.close();
}
fin.close();
}
}
@Test public void write100KFiles() throws Throwable {
withTemporaryArchive("write100KFiles", new ZipOutputTest() {
public void test(File f, ZipArchiveOutputStream zos)
throws IOException {
for (int i = 0; i < ONE_HUNDRED_THOUSAND; i++) {
ZipArchiveEntry zae =
new ZipArchiveEntry(String.valueOf(i));
zae.setSize(0);
zos.putArchiveEntry(zae);
zos.closeArchiveEntry();
}
zos.close();
RandomAccessFile a = new RandomAccessFile(f, "r");
try {
final long end = a.length();
// validate "end of central directory" is at
// the end of the file and contains the magic
// value 0xFFFF as "number of entries".
a.seek(end
- 22 /* length of EOCD without file comment */);
byte[] eocd = new byte[12];
a.readFully(eocd);
assertArrayEquals(new byte[] {
// sig
(byte) 0x50, (byte) 0x4b, 5, 6,
// disk numbers
0, 0, 0, 0,
// entries
(byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff,
}, eocd);
} finally {
a.close();
}
}
});
}
static interface ZipOutputTest {
void test(File f, ZipArchiveOutputStream zos) throws IOException;
}
private static void withTemporaryArchive(String testName,
ZipOutputTest test)
throws Throwable {
File f = getTempFile(testName);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(f);
try {
test.test(f, zos);
} catch (IOException ex) {
System.err.println("Failed to write archive because of: "
+ ex.getMessage()
+ " - likely not enough disk space.");
assumeTrue(false);
} finally {
zos.close();
}
}
private static File getFile(String name) throws Throwable {
URL url = Zip64SupportTest.class.getResource(name);
assumeNotNull(url);
File file = new File(new URI(url.toString()));
assumeTrue(file.exists());
return file;
}
private static File get5GBZerosFile() throws Throwable {
return getFile("/5GB_of_Zeros.zip");
}
private static File get100KFileFile() throws Throwable {
return getFile("/100k_Files.zip");
}
private static File getTempFile(String testName) throws Throwable {
File f = File.createTempFile("commons-compress-" + testName, ".zip");
f.deleteOnExit();
return f;
}
}
| completely validate the structure of ZIP64 'end of central directory' structures. COMPRESS-150
git-svn-id: ff1094eb2de31cc2ef640fd2700fc2c732d8aec3@1152222 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportTest.java | completely validate the structure of ZIP64 'end of central directory' structures. COMPRESS-150 | <ide><path>rc/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportTest.java
<ide> (byte) 0xff, (byte) 0xff,
<ide> (byte) 0xff, (byte) 0xff,
<ide> }, eocd);
<add>
<add> // validate "Zip64 end of central directory
<add> // locator" is right in front of the EOCD and
<add> // the location of the "Zip64 end of central
<add> // directory record" seems correct
<add> long expectedZ64EocdOffset = end - 22 /* eocd.length */
<add> - 20 /* z64 eocd locator.length */
<add> - 56 /* z64 eocd without extensible data sector */;
<add> byte[] loc =
<add> ZipEightByteInteger.getBytes(expectedZ64EocdOffset);
<add> a.seek(end - 22 - 20);
<add> byte[] z64EocdLoc = new byte[20];
<add> a.readFully(z64EocdLoc);
<add> assertArrayEquals(new byte[] {
<add> // sig
<add> (byte) 0x50, (byte) 0x4b, 6, 7,
<add> // disk numbers
<add> 0, 0, 0, 0,
<add> // location of Zip64 EOCD,
<add> loc[0], loc[1], loc[2], loc[3],
<add> loc[4], loc[5], loc[6], loc[7],
<add> // total number of disks
<add> 1, 0, 0, 0,
<add> }, z64EocdLoc);
<add>
<add> // validate "Zip64 end of central directory
<add> // record" is where it is supposed to be, the
<add> // known values are fine and read the location
<add> // of the central directory from it
<add> a.seek(expectedZ64EocdOffset);
<add> byte[] z64EocdStart = new byte[40];
<add> a.readFully(z64EocdStart);
<add> assertArrayEquals(new byte[] {
<add> // sig
<add> (byte) 0x50, (byte) 0x4b, 6, 6,
<add> // size of z64 EOCD
<add> 44, 0, 0, 0,
<add> 0, 0, 0, 0,
<add> // version made by
<add> 45, 0,
<add> // version needed to extract
<add> 45, 0,
<add> // disk numbers
<add> 0, 0, 0, 0,
<add> 0, 0, 0, 0,
<add> // number of entries 100k = 0x186A0
<add> (byte) 0xA0, (byte) 0x86, 1, 0,
<add> 0, 0, 0, 0,
<add> (byte) 0xA0, (byte) 0x86, 1, 0,
<add> 0, 0, 0, 0,
<add> }, z64EocdStart);
<add> a.seek(expectedZ64EocdOffset + 48 /* skip size */);
<add> byte[] cdOffset = new byte[8];
<add> a.readFully(cdOffset);
<add> long cdLoc = ZipEightByteInteger.getLongValue(cdOffset);
<add>
<add> // finally verify there really is a central
<add> // directory entry where the Zip64 EOCD claims
<add> a.seek(cdLoc);
<add> byte[] sig = new byte[4];
<add> a.readFully(sig);
<add> assertArrayEquals(new byte[] {
<add> (byte) 0x50, (byte) 0x4b, 1, 2,
<add> }, sig);
<ide> } finally {
<ide> a.close();
<ide> } |
|
Java | apache-2.0 | 1e044188e967c360af6c4cb7e14e3693233a9b0b | 0 | ChiralBehaviors/Kramer,ChiralBehaviors/Kramer | /**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout;
import static com.chiralbehaviors.layout.LayoutProvider.snap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.chiralbehaviors.layout.control.JsonControl;
import com.chiralbehaviors.layout.control.NestedTable;
import com.chiralbehaviors.layout.control.Outline;
import com.chiralbehaviors.layout.schema.Relation;
import com.chiralbehaviors.layout.schema.SchemaNode;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import javafx.scene.Parent;
import javafx.scene.control.Control;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.util.Pair;
/**
*
* @author halhildebrand
*
*/
public class RelationLayout extends SchemaNodeLayout {
boolean useTable = false;
private int averageCardinality;
private double columnHeaderHeight;
private final List<ColumnSet> columnSets = new ArrayList<>();
private double labelWidth;
private int maxCardinality;
private double outlineWidth = 0;
private final Relation r;
private double rowHeight = -1;
private double scroll = 0.0;
private boolean singular;
private double tableColumnWidth = 0;
public RelationLayout(LayoutProvider layout, Relation r) {
super(layout);
this.r = r;
}
@Override
public void adjustHeight(double delta) {
super.adjustHeight(delta);
if (useTable) {
List<SchemaNode> children = r.getChildren();
double subDelta = delta / children.size();
if (delta >= 1.0) {
children.forEach(f -> f.adjustHeight(subDelta));
}
return;
}
double subDelta = delta / columnSets.size();
if (subDelta >= 1.0) {
columnSets.forEach(c -> c.adjustHeight(subDelta));
}
}
public void apply(ListCell<JsonNode> cell) {
layout.getModel()
.apply(cell, r);
}
public void apply(ListView<JsonNode> list) {
layout.getModel()
.apply(list, r);
}
public double baseOutlineCellHeight(double cellHeight) {
return cellHeight - layout.getListCellVerticalInset();
}
public double baseRowCellHeight(double extended) {
return extended - layout.getListCellVerticalInset();
}
public Region buildColumnHeader() {
HBox header = new HBox();
List<SchemaNode> children = r.getChildren();
children.forEach(c -> header.getChildren()
.add(c.buildColumnHeader()
.apply(columnHeaderHeight)));
return header;
}
public JsonControl buildControl(int cardinality,
Function<JsonNode, JsonNode> extractor) {
return useTable ? r.buildNestedTable(extractor, cardinality)
: r.buildOutline(extractor, cardinality);
}
public JsonControl buildNestedTable(int cardinality) {
return new NestedTable(this).build(resolveCardinality(cardinality),
this);
}
public JsonControl buildOutline(Function<JsonNode, JsonNode> extractor,
int cardinality) {
return new Outline(this).build(height, columnSets, extractor,
resolveCardinality(cardinality), this);
}
public double calculateTableColumnWidth() {
return r.getChildren()
.stream()
.mapToDouble(c -> c.calculateTableColumnWidth())
.sum()
+ layout.getNestedInset();
}
public double cellHeight(int card, double width) {
if (height > 0) {
return height;
}
int cardinality = resolveCardinality(card);
if (!useTable) {
height = outlineHeight(cardinality);
} else {
columnHeaderHeight = r.getChildren()
.stream()
.mapToDouble(c -> c.columnHeaderHeight())
.max()
.orElse(0.0);
double elementHeight = elementHeight();
rowHeight = rowHeight(elementHeight);
height = (cardinality
* (elementHeight + layout.getListCellVerticalInset()))
+ layout.getListVerticalInset() + columnHeaderHeight;
}
return height;
}
@Override
public Function<Double, Region> columnHeader() {
List<SchemaNode> children = r.getChildren();
List<Function<Double, Region>> nestedHeaders = children.stream()
.map(c -> c.buildColumnHeader())
.collect(Collectors.toList());
return rendered -> {
VBox columnHeader = new VBox();
HBox nested = new HBox();
double width = getJustifiedTableColumnWidth()
+ columnHeaderIndentation;
columnHeader.setMinSize(width, rendered);
columnHeader.setMaxSize(width, rendered);
double half = snap(rendered / 2.0);
columnHeader.getChildren()
.add(layout.label(width, r.getLabel(), half));
columnHeader.getChildren()
.add(nested);
nestedHeaders.forEach(n -> {
nested.getChildren()
.add(n.apply(half));
});
return columnHeader;
};
}
@Override
public void compress(double justified, boolean ignored) {
if (useTable) {
r.justify(justified);
return;
}
columnSets.clear();
justifiedWidth = baseOutlineWidth(justified);
List<SchemaNode> children = r.getChildren();
columnSets.clear();
ColumnSet current = null;
double halfWidth = snap(justifiedWidth / 2d);
for (SchemaNode child : children) {
double childWidth = labelWidth + child.layoutWidth();
if (childWidth > halfWidth || current == null) {
current = new ColumnSet();
columnSets.add(current);
current.add(child);
if (childWidth > halfWidth) {
current = null;
}
} else {
current.add(child);
}
}
columnSets.forEach(cs -> cs.compress(averageCardinality, justifiedWidth,
labelWidth, scroll > 0.0));
}
@Override
public JsonNode extractFrom(JsonNode node) {
return r.extractFrom(node);
}
public void forEach(Consumer<? super SchemaNode> action) {
List<SchemaNode> children = r.getChildren();
children.forEach(c -> action.accept(c));
}
public int getAverageCardinality() {
return averageCardinality;
}
public double getColumnHeaderHeight() {
if (columnHeaderHeight <= 0) {
columnHeaderHeight = (layout.getTextLineHeight()
+ layout.getTextVerticalInset())
+ r.getChildren()
.stream()
.mapToDouble(c -> c.columnHeaderHeight())
.max()
.orElse(0.0);
}
return columnHeaderHeight;
}
public double getJustifiedCellWidth() {
return justifiedWidth + layout.getListCellHorizontalInset();
}
@Override
public double getJustifiedTableColumnWidth() {
return justifiedWidth + layout.getNestedInset();
}
public double getLabelWidth() {
return labelWidth;
}
public double getRowHeight() {
return rowHeight;
}
public String getStyleClass() {
return r.getField();
}
public boolean isSingular() {
return singular;
}
@Override
public double justify(double justifed) {
double available = justifed - layout.getNestedCellInset();
assert available >= tableColumnWidth : String.format("%s justified width incorrect %s < %s",
r.getLabel(),
available,
tableColumnWidth);
double slack = Math.max(0, available - tableColumnWidth);
List<SchemaNode> children = r.getChildren();
justifiedWidth = children.stream()
.mapToDouble(child -> {
double childWidth = child.tableColumnWidth();
double additional = slack
* (childWidth
/ tableColumnWidth);
double childJustified = snap(additional
+ childWidth);
return child.justify(childJustified);
})
.sum();
assert justifiedWidth > 0 : String.format("%s jw <= 0: %s", r.getLabel(), justifiedWidth);
return justifiedWidth + layout.getNestedInset();
}
@Override
public double layout(double width) {
clear();
double available = baseOutlineWidth(snap(width - labelWidth));
assert available > 0;
outlineWidth = r.getChildren()
.stream()
.mapToDouble(c -> c.layout(available))
.max()
.orElse(0.0)
+ labelWidth;
double tableWidth = calculateTableColumnWidth();
if (width >= tableWidth && tableWidth <= outlineWidth(outlineWidth)) {
return nestTableColumn(Indent.TOP, 0);
}
return outlineWidth(outlineWidth);
}
@Override
public double layoutWidth() {
return useTable ? tableColumnWidth() : outlineWidth(outlineWidth);
}
@Override
public double measure(JsonNode datum, boolean isSingular) {
clear();
double sum = 0;
outlineWidth = 0;
singular = isSingular;
int singularChildren = 0;
maxCardinality = 0;
List<SchemaNode> children = r.getChildren();
for (SchemaNode child : children) {
ArrayNode aggregate = JsonNodeFactory.instance.arrayNode();
int cardSum = 0;
boolean childSingular = false;
List<JsonNode> data = datum.isArray() ? new ArrayList<>(datum.size())
: Arrays.asList(datum);
if (datum.isArray()) {
datum.forEach(n -> data.add(n));
}
for (JsonNode node : data) {
JsonNode sub = node.get(child.getField());
if (sub instanceof ArrayNode) {
childSingular = false;
aggregate.addAll((ArrayNode) sub);
cardSum += sub.size();
} else {
childSingular = true;
aggregate.add(sub);
}
}
if (childSingular) {
singularChildren += 1;
} else {
sum += data.size() == 0 ? 1 : Math.round(cardSum / data.size());
}
outlineWidth = snap(Math.max(outlineWidth,
child.measure(aggregate, childSingular,
layout)));
maxCardinality = Math.max(maxCardinality, data.size());
}
int effectiveChildren = children.size() - singularChildren;
averageCardinality = Math.max(1,
Math.min(4,
effectiveChildren == 0 ? 1
: (int) Math.ceil(sum
/ effectiveChildren)));
labelWidth = children.stream()
.mapToDouble(child -> child.getLabelWidth())
.max()
.getAsDouble();
outlineWidth = snap(labelWidth + outlineWidth);
maxCardinality = Math.max(1, maxCardinality);
if (!singular && maxCardinality > averageCardinality) {
scroll = layout.getScrollWidth();
}
return r.outlineWidth();
}
@Override
public double nestTableColumn(Indent indent, double indentation) {
columnHeaderIndentation = indentation;
useTable = true;
rowHeight = -1.0;
columnHeaderHeight = -1.0;
height = -1.0;
tableColumnWidth = snap(r.getChildren()
.stream()
.mapToDouble(c -> {
Indent child = indent(indent, c);
return c.nestTableColumn(child,
indent.indent(child,
layout,
indentation,
c.isRelation()));
})
.sum());
return tableColumnWidth + indentation;
}
public double outlineCellHeight(double baseHeight) {
return baseHeight + layout.getListCellVerticalInset();
}
public Pair<Consumer<JsonNode>, Parent> outlineElement(int cardinality,
double labelWidth,
Function<JsonNode, JsonNode> extractor,
double justified) {
Control labelControl = label(labelWidth, r.getLabel());
labelControl.setMinWidth(labelWidth);
labelControl.setMaxWidth(labelWidth);
JsonControl control = r.buildControl(cardinality, extractor);
double available = justified - labelWidth;
control.setMinWidth(available);
control.setMaxWidth(available);
control.setMinHeight(height);
control.setMaxHeight(height);
Pane box = new HBox();
box.getStyleClass()
.add(r.getField());
box.setMinWidth(justified);
box.setMaxWidth(justified);
box.setMinHeight(height);
box.setMaxHeight(height);
box.getChildren()
.add(labelControl);
box.getChildren()
.add(control);
return new Pair<>(item -> {
if (item == null) {
return;
}
control.setItem(extractor.apply(item) == null ? null
: extractor.apply(item)
.get(r.getField()));
}, box);
}
public double outlineWidth() {
return outlineWidth(outlineWidth);
}
public int resolvedCardinality() {
return resolveCardinality(averageCardinality);
}
public double rowHeight(int cardinality, double justified) {
rowHeight = rowHeight(elementHeight());
height = (cardinality * rowHeight) + layout.getListVerticalInset();
return height;
}
public double tableColumnWidth() {
assert tableColumnWidth > 0.0 : String.format("%s tcw <= 0: %s",
r.getLabel(),
tableColumnWidth);
return tableColumnWidth + layout.getNestedInset();
}
@Override
public String toString() {
return String.format("RelationLayout [r=%s x %s:%s, {%s, %s, %s} ]",
r.getField(), averageCardinality, height,
outlineWidth, tableColumnWidth, justifiedWidth);
}
protected double baseOutlineWidth(double width) {
return snap(width - layout.getNestedInset());
}
@Override
protected void clear() {
super.clear();
useTable = false;
tableColumnWidth = -1.0;
scroll = 0.0;
}
protected double elementHeight() {
return r.getChildren()
.stream()
.mapToDouble(child -> child.rowHeight(averageCardinality,
justifiedWidth))
.max()
.getAsDouble();
}
protected Indent indent(Indent parent, SchemaNode child) {
List<SchemaNode> children = r.getChildren();
boolean isFirst = isFirst(child, children);
boolean isLast = isLast(child, children);
if (isFirst && isLast) {
return Indent.SINGULAR;
}
if (isFirst) {
return Indent.LEFT;
} else if (isLast) {
return Indent.RIGHT;
} else {
return Indent.NONE;
}
}
protected boolean isFirst(SchemaNode child, List<SchemaNode> children) {
return child.equals(children.get(0));
}
protected boolean isLast(SchemaNode child, List<SchemaNode> children) {
return child.equals(children.get(children.size() - 1));
}
protected double outlineHeight(int cardinality) {
return outlineHeight(cardinality, columnSets.stream()
.mapToDouble(cs -> cs.getCellHeight())
.sum());
}
protected double outlineHeight(int cardinality, double elementHeight) {
return (cardinality
* (elementHeight + layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
protected double outlineWidth(double outlineWidth) {
return outlineWidth + layout.getNestedInset();
}
protected int resolveCardinality(int cardinality) {
return singular ? 1 : Math.min(cardinality, maxCardinality);
}
protected double rowHeight(double elementHeight) {
return elementHeight + layout.getListCellVerticalInset();
}
} | kramer/src/main/java/com/chiralbehaviors/layout/RelationLayout.java | /**
* Copyright (c) 2017 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout;
import static com.chiralbehaviors.layout.LayoutProvider.snap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.chiralbehaviors.layout.control.JsonControl;
import com.chiralbehaviors.layout.control.NestedTable;
import com.chiralbehaviors.layout.control.Outline;
import com.chiralbehaviors.layout.schema.Relation;
import com.chiralbehaviors.layout.schema.SchemaNode;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import javafx.scene.Parent;
import javafx.scene.control.Control;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.util.Pair;
/**
*
* @author halhildebrand
*
*/
public class RelationLayout extends SchemaNodeLayout {
boolean useTable = false;
private int averageCardinality;
private double columnHeaderHeight;
private final List<ColumnSet> columnSets = new ArrayList<>();
private double labelWidth;
private int maxCardinality;
private double outlineWidth = 0;
private final Relation r;
private double rowHeight = -1;
private double scroll = 0.0;
private boolean singular;
private double tableColumnWidth = 0;
public RelationLayout(LayoutProvider layout, Relation r) {
super(layout);
this.r = r;
}
@Override
public void adjustHeight(double delta) {
super.adjustHeight(delta);
if (useTable) {
List<SchemaNode> children = r.getChildren();
double subDelta = delta / children.size();
if (delta >= 1.0) {
children.forEach(f -> f.adjustHeight(subDelta));
}
return;
}
double subDelta = delta / columnSets.size();
if (subDelta >= 1.0) {
columnSets.forEach(c -> c.adjustHeight(subDelta));
}
}
public void apply(ListCell<JsonNode> cell) {
layout.getModel()
.apply(cell, r);
}
public void apply(ListView<JsonNode> list) {
layout.getModel()
.apply(list, r);
}
public double baseOutlineCellHeight(double cellHeight) {
return cellHeight - layout.getListCellVerticalInset();
}
public double baseRowCellHeight(double extended) {
return extended - layout.getListCellVerticalInset();
}
public Region buildColumnHeader() {
HBox header = new HBox();
List<SchemaNode> children = r.getChildren();
children.forEach(c -> header.getChildren()
.add(c.buildColumnHeader()
.apply(columnHeaderHeight)));
return header;
}
public JsonControl buildControl(int cardinality,
Function<JsonNode, JsonNode> extractor) {
return useTable ? r.buildNestedTable(extractor, cardinality)
: r.buildOutline(extractor, cardinality);
}
public JsonControl buildNestedTable(int cardinality) {
return new NestedTable(this).build(resolveCardinality(cardinality),
this);
}
public JsonControl buildOutline(Function<JsonNode, JsonNode> extractor,
int cardinality) {
return new Outline(this).build(height, columnSets, extractor,
resolveCardinality(cardinality), this);
}
public double calculateTableColumnWidth() {
return r.getChildren()
.stream()
.mapToDouble(c -> c.calculateTableColumnWidth())
.sum()
+ layout.getNestedInset();
}
public double cellHeight(int card, double width) {
if (height > 0) {
return height;
}
int cardinality = resolveCardinality(card);
if (!useTable) {
height = outlineHeight(cardinality);
} else {
columnHeaderHeight = r.getChildren()
.stream()
.mapToDouble(c -> c.columnHeaderHeight())
.max()
.orElse(0.0);
double elementHeight = elementHeight();
rowHeight = rowHeight(elementHeight);
height = (cardinality
* (elementHeight + layout.getListCellVerticalInset()))
+ layout.getListVerticalInset() + columnHeaderHeight;
}
return height;
}
@Override
public Function<Double, Region> columnHeader() {
List<SchemaNode> children = r.getChildren();
List<Function<Double, Region>> nestedHeaders = children.stream()
.map(c -> c.buildColumnHeader())
.collect(Collectors.toList());
return rendered -> {
VBox columnHeader = new VBox();
HBox nested = new HBox();
double width = getJustifiedTableColumnWidth()
+ columnHeaderIndentation;
columnHeader.setMinSize(width, rendered);
columnHeader.setMaxSize(width, rendered);
double half = snap(rendered / 2.0);
columnHeader.getChildren()
.add(layout.label(width, r.getLabel(), half));
columnHeader.getChildren()
.add(nested);
nestedHeaders.forEach(n -> {
nested.getChildren()
.add(n.apply(half));
});
return columnHeader;
};
}
@Override
public void compress(double justified, boolean ignored) {
if (useTable) {
r.justify(justified);
return;
}
columnSets.clear();
justifiedWidth = baseOutlineWidth(justified);
List<SchemaNode> children = r.getChildren();
columnSets.clear();
ColumnSet current = null;
double halfWidth = snap(justifiedWidth / 2d);
for (SchemaNode child : children) {
double childWidth = labelWidth + child.layoutWidth();
if (childWidth > halfWidth || current == null) {
current = new ColumnSet();
columnSets.add(current);
current.add(child);
if (childWidth > halfWidth) {
current = null;
}
} else {
current.add(child);
}
}
columnSets.forEach(cs -> cs.compress(averageCardinality, justifiedWidth,
labelWidth, scroll > 0.0));
}
@Override
public JsonNode extractFrom(JsonNode node) {
return r.extractFrom(node);
}
public void forEach(Consumer<? super SchemaNode> action) {
List<SchemaNode> children = r.getChildren();
children.forEach(c -> action.accept(c));
}
public int getAverageCardinality() {
return averageCardinality;
}
public double getColumnHeaderHeight() {
if (columnHeaderHeight <= 0) {
columnHeaderHeight = (layout.getTextLineHeight()
+ layout.getTextVerticalInset())
+ r.getChildren()
.stream()
.mapToDouble(c -> c.columnHeaderHeight())
.max()
.orElse(0.0);
}
return columnHeaderHeight;
}
public double getJustifiedCellWidth() {
return justifiedWidth + layout.getListCellHorizontalInset();
}
@Override
public double getJustifiedTableColumnWidth() {
return justifiedWidth + layout.getNestedInset();
}
public double getLabelWidth() {
return labelWidth;
}
public double getRowHeight() {
return rowHeight;
}
public String getStyleClass() {
return r.getField();
}
public boolean isSingular() {
return singular;
}
@Override
public double justify(double justifed) {
double available = justifed - layout.getNestedCellInset();
assert available >= tableColumnWidth : String.format("%s justified width incorrect %s < %s",
r.getLabel(),
available,
tableColumnWidth);
double slack = Math.max(0, available - tableColumnWidth);
List<SchemaNode> children = r.getChildren();
justifiedWidth = children.stream()
.mapToDouble(child -> {
double childWidth = child.tableColumnWidth();
double additional = slack
* (childWidth
/ tableColumnWidth);
double childJustified = snap(additional
+ childWidth);
return child.justify(childJustified);
})
.sum();
return justifiedWidth + layout.getNestedInset();
}
@Override
public double layout(double width) {
clear();
double available = baseOutlineWidth(snap(width - labelWidth));
assert available > 0;
outlineWidth = r.getChildren()
.stream()
.mapToDouble(c -> c.layout(available))
.max()
.orElse(0.0)
+ labelWidth;
double tableWidth = calculateTableColumnWidth();
if (tableWidth <= outlineWidth(outlineWidth)) {
return nestTableColumn(Indent.TOP, 0);
}
return outlineWidth(outlineWidth);
}
@Override
public double layoutWidth() {
return useTable ? tableColumnWidth() : outlineWidth(outlineWidth);
}
@Override
public double measure(JsonNode datum, boolean isSingular) {
clear();
double sum = 0;
outlineWidth = 0;
singular = isSingular;
int singularChildren = 0;
maxCardinality = 0;
List<SchemaNode> children = r.getChildren();
for (SchemaNode child : children) {
ArrayNode aggregate = JsonNodeFactory.instance.arrayNode();
int cardSum = 0;
boolean childSingular = false;
List<JsonNode> data = datum.isArray() ? new ArrayList<>(datum.size())
: Arrays.asList(datum);
if (datum.isArray()) {
datum.forEach(n -> data.add(n));
}
for (JsonNode node : data) {
JsonNode sub = node.get(child.getField());
if (sub instanceof ArrayNode) {
childSingular = false;
aggregate.addAll((ArrayNode) sub);
cardSum += sub.size();
} else {
childSingular = true;
aggregate.add(sub);
}
}
if (childSingular) {
singularChildren += 1;
} else {
sum += data.size() == 0 ? 1 : Math.round(cardSum / data.size());
}
outlineWidth = snap(Math.max(outlineWidth,
child.measure(aggregate, childSingular,
layout)));
maxCardinality = Math.max(maxCardinality, data.size());
}
int effectiveChildren = children.size() - singularChildren;
averageCardinality = Math.max(1,
Math.min(4,
effectiveChildren == 0 ? 1
: (int) Math.ceil(sum
/ effectiveChildren)));
labelWidth = children.stream()
.mapToDouble(child -> child.getLabelWidth())
.max()
.getAsDouble();
outlineWidth = snap(labelWidth + outlineWidth);
maxCardinality = Math.max(1, maxCardinality);
if (!singular && maxCardinality > averageCardinality) {
scroll = layout.getScrollWidth();
}
return r.outlineWidth();
}
@Override
public double nestTableColumn(Indent indent, double indentation) {
columnHeaderIndentation = indentation;
useTable = true;
rowHeight = -1.0;
columnHeaderHeight = -1.0;
height = -1.0;
tableColumnWidth = snap(r.getChildren()
.stream()
.mapToDouble(c -> {
Indent child = indent(indent, c);
return c.nestTableColumn(child,
indent.indent(child,
layout,
indentation,
c.isRelation()));
})
.sum());
return tableColumnWidth + indentation;
}
public double outlineCellHeight(double baseHeight) {
return baseHeight + layout.getListCellVerticalInset();
}
public Pair<Consumer<JsonNode>, Parent> outlineElement(int cardinality,
double labelWidth,
Function<JsonNode, JsonNode> extractor,
double justified) {
Control labelControl = label(labelWidth, r.getLabel());
labelControl.setMinWidth(labelWidth);
labelControl.setMaxWidth(labelWidth);
JsonControl control = r.buildControl(cardinality, extractor);
double available = justified - labelWidth;
control.setMinWidth(available);
control.setMaxWidth(available);
control.setMinHeight(height);
control.setMaxHeight(height);
Pane box = new HBox();
box.getStyleClass()
.add(r.getField());
box.setMinWidth(justified);
box.setMaxWidth(justified);
box.setMinHeight(height);
box.setMaxHeight(height);
box.getChildren()
.add(labelControl);
box.getChildren()
.add(control);
return new Pair<>(item -> {
if (item == null) {
return;
}
control.setItem(extractor.apply(item) == null ? null
: extractor.apply(item)
.get(r.getField()));
}, box);
}
public double outlineWidth() {
return outlineWidth(outlineWidth);
}
public int resolvedCardinality() {
return resolveCardinality(averageCardinality);
}
public double rowHeight(int cardinality, double justified) {
rowHeight = rowHeight(elementHeight());
height = (cardinality * rowHeight) + layout.getListVerticalInset();
return height;
}
public double tableColumnWidth() {
assert tableColumnWidth > 0.0;
return tableColumnWidth + layout.getNestedInset();
}
@Override
public String toString() {
return String.format("RelationLayout [r=%s x %s:%s, {%s, %s, %s} ]",
r.getField(), averageCardinality, height,
outlineWidth, tableColumnWidth, justifiedWidth);
}
protected double baseOutlineWidth(double width) {
return snap(width - layout.getNestedInset());
}
@Override
protected void clear() {
super.clear();
tableColumnWidth = -1.0;
scroll = 0.0;
}
protected double elementHeight() {
return r.getChildren()
.stream()
.mapToDouble(child -> child.rowHeight(averageCardinality,
justifiedWidth))
.max()
.getAsDouble();
}
protected Indent indent(Indent parent, SchemaNode child) {
List<SchemaNode> children = r.getChildren();
boolean isFirst = isFirst(child, children);
boolean isLast = isLast(child, children);
if (isFirst && isLast) {
return Indent.SINGULAR;
}
if (isFirst) {
return Indent.LEFT;
} else if (isLast) {
return Indent.RIGHT;
} else {
return Indent.NONE;
}
}
protected boolean isFirst(SchemaNode child, List<SchemaNode> children) {
return child.equals(children.get(0));
}
protected boolean isLast(SchemaNode child, List<SchemaNode> children) {
return child.equals(children.get(children.size() - 1));
}
protected double outlineHeight(int cardinality) {
return outlineHeight(cardinality, columnSets.stream()
.mapToDouble(cs -> cs.getCellHeight())
.sum());
}
protected double outlineHeight(int cardinality, double elementHeight) {
return (cardinality
* (elementHeight + layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
protected double outlineWidth(double outlineWidth) {
return outlineWidth + layout.getNestedInset();
}
protected int resolveCardinality(int cardinality) {
return singular ? 1 : Math.min(cardinality, maxCardinality);
}
protected double rowHeight(double elementHeight) {
return elementHeight + layout.getListCellVerticalInset();
}
} | clear previous nested table decisions when laying out.
Somehow lost this a while ago :( | kramer/src/main/java/com/chiralbehaviors/layout/RelationLayout.java | clear previous nested table decisions when laying out. | <ide><path>ramer/src/main/java/com/chiralbehaviors/layout/RelationLayout.java
<ide> }
<ide>
<ide> @Override
<del> public double justify(double justifed) {
<add> public double justify(double justifed) {
<ide> double available = justifed - layout.getNestedCellInset();
<ide> assert available >= tableColumnWidth : String.format("%s justified width incorrect %s < %s",
<ide> r.getLabel(),
<ide> return child.justify(childJustified);
<ide> })
<ide> .sum();
<add> assert justifiedWidth > 0 : String.format("%s jw <= 0: %s", r.getLabel(), justifiedWidth);
<ide> return justifiedWidth + layout.getNestedInset();
<ide> }
<ide>
<ide> .orElse(0.0)
<ide> + labelWidth;
<ide> double tableWidth = calculateTableColumnWidth();
<del> if (tableWidth <= outlineWidth(outlineWidth)) {
<add> if (width >= tableWidth && tableWidth <= outlineWidth(outlineWidth)) {
<ide> return nestTableColumn(Indent.TOP, 0);
<ide> }
<ide> return outlineWidth(outlineWidth);
<ide> }
<ide>
<ide> public double tableColumnWidth() {
<del> assert tableColumnWidth > 0.0;
<add> assert tableColumnWidth > 0.0 : String.format("%s tcw <= 0: %s",
<add> r.getLabel(),
<add> tableColumnWidth);
<ide> return tableColumnWidth + layout.getNestedInset();
<ide> }
<ide>
<ide> @Override
<ide> protected void clear() {
<ide> super.clear();
<add> useTable = false;
<ide> tableColumnWidth = -1.0;
<ide> scroll = 0.0;
<ide> } |
|
Java | lgpl-2.1 | c1cebca41966c29197a1e94f84c1af10ffd02eb8 | 0 | cytoscape/welcome | package org.cytoscape.welcome.internal;
import static org.cytoscape.work.ServiceProperties.IN_TOOL_BAR;
import static org.cytoscape.work.ServiceProperties.MENU_GRAVITY;
import static org.cytoscape.work.ServiceProperties.PREFERRED_MENU;
import static org.cytoscape.work.ServiceProperties.TITLE;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.cytoscape.application.CyApplicationConfiguration;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.CyVersion;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.io.datasource.DataSourceManager;
import org.cytoscape.io.util.RecentlyOpenedTracker;
import org.cytoscape.property.CyProperty;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.task.analyze.AnalyzeNetworkCollectionTaskFactory;
import org.cytoscape.task.read.LoadNetworkURLTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.visualize.ApplyPreferredLayoutTaskFactory;
import org.cytoscape.util.swing.OpenBrowser;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.presentation.property.values.BendFactory;
import org.cytoscape.view.vizmap.VisualMappingFunctionFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.welcome.internal.panel.CreateNewNetworkPanel;
import org.cytoscape.welcome.internal.panel.NewsAndLinkPanel;
import org.cytoscape.welcome.internal.panel.OpenPanel;
import org.cytoscape.welcome.internal.panel.StatusPanel;
import org.cytoscape.welcome.internal.task.ApplySelectedLayoutTaskFactory;
import org.cytoscape.welcome.internal.task.GenerateCustomStyleTaskFactory;
import org.cytoscape.work.ServiceProperties;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.swing.DialogTaskManager;
import org.osgi.framework.BundleContext;
public class CyActivator extends AbstractCyActivator {
public CyActivator() {
super();
}
public void start(BundleContext bc) {
final CyServiceRegistrar registrar = getService(bc, CyServiceRegistrar.class);
CyApplicationManager applicationManager = getService(bc, CyApplicationManager.class);
CyVersion cyVersion = getService(bc, CyVersion.class);
final ApplyPreferredLayoutTaskFactory applyPreferredLayoutTaskFactory = getService(bc,
ApplyPreferredLayoutTaskFactory.class);
BendFactory bendFactory = getService(bc, BendFactory.class);
VisualMappingManager vmm = getService(bc, VisualMappingManager.class);
VisualStyleFactory vsFactoryServiceRef = getService(bc, VisualStyleFactory.class);
VisualMappingFunctionFactory continupousMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=continuous)");
VisualMappingFunctionFactory passthroughMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=passthrough)");
VisualMappingFunctionFactory discreteMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=discrete)");
VisualStyleBuilder vsBuilder = new VisualStyleBuilder(vsFactoryServiceRef, continupousMappingFactoryRef,
discreteMappingFactoryRef, passthroughMappingFactoryRef, bendFactory);
AnalyzeNetworkCollectionTaskFactory analyzeNetworkCollectionTaskFactory = getService(bc,
AnalyzeNetworkCollectionTaskFactory.class);
CySwingApplication cytoscapeDesktop = getService(bc, CySwingApplication.class);
OpenBrowser openBrowserServiceRef = getService(bc, OpenBrowser.class);
RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc, RecentlyOpenedTracker.class);
OpenSessionTaskFactory openSessionTaskFactory = getService(bc, OpenSessionTaskFactory.class);
DialogTaskManager dialogTaskManagerServiceRef = getService(bc, DialogTaskManager.class);
TaskFactory importNetworkFileTF = getService(bc, TaskFactory.class, "(id=loadNetworkFileTaskFactory)");
LoadNetworkURLTaskFactory importNetworkTF = getService(bc, LoadNetworkURLTaskFactory.class);
CyApplicationConfiguration cyApplicationConfigurationServiceRef = getService(bc,
CyApplicationConfiguration.class);
DataSourceManager dsManagerServiceRef = getService(bc, DataSourceManager.class);
@SuppressWarnings("unchecked")
CyProperty<Properties> cytoscapePropertiesServiceRef = getService(bc, CyProperty.class,
"(cyPropertyName=cytoscape3.props)");
// Build Child Panels
final OpenPanel openPanel = new OpenPanel(recentlyOpenedTrackerServiceRef, dialogTaskManagerServiceRef,
openSessionTaskFactory);
final CreateNewNetworkPanel createNewNetworkPanel = new CreateNewNetworkPanel(bc, dialogTaskManagerServiceRef,
importNetworkFileTF, importNetworkTF, dsManagerServiceRef);
registerAllServices(bc, createNewNetworkPanel, new Properties());
// TODO: implement contents
final StatusPanel statusPanel = new StatusPanel(cyVersion);
final NewsAndLinkPanel helpPanel = new NewsAndLinkPanel(statusPanel, openBrowserServiceRef,
cytoscapePropertiesServiceRef);
// Show Welcome Screen
final WelcomeScreenAction welcomeScreenAction = new WelcomeScreenAction(createNewNetworkPanel, openPanel,
helpPanel, cytoscapePropertiesServiceRef, cytoscapeDesktop);
registerAllServices(bc, welcomeScreenAction, new Properties());
// Export preset tasks
final GenerateCustomStyleTaskFactory generateCustomStyleTaskFactory = new GenerateCustomStyleTaskFactory(
analyzeNetworkCollectionTaskFactory, applicationManager, vsBuilder, vmm);
Properties generateCustomStyleTaskFactoryProps = new Properties();
generateCustomStyleTaskFactoryProps.setProperty(PREFERRED_MENU, "Tools.Workflow");
generateCustomStyleTaskFactoryProps.setProperty(MENU_GRAVITY, "20.0");
generateCustomStyleTaskFactoryProps.setProperty(TITLE,
"Analyze selected networks and create custom Visual Styles");
generateCustomStyleTaskFactoryProps.setProperty(IN_TOOL_BAR, "false");
generateCustomStyleTaskFactoryProps.setProperty(ServiceProperties.ENABLE_FOR, "networkAndView");
registerAllServices(bc, generateCustomStyleTaskFactory, generateCustomStyleTaskFactoryProps);
// This is a preset task, so register it first.
final Map<String, String> propMap = new HashMap<String, String>();
propMap.put(CreateNewNetworkPanel.WORKFLOW_ID, "generateCustomStyleTaskFactory");
propMap.put(CreateNewNetworkPanel.WORKFLOW_NAME, "Analyze network and create custom Visual Style");
propMap.put(CreateNewNetworkPanel.WORKFLOW_DESCRIPTION,
"Analyze current/selected networks and create custom Visual Style for each network.");
createNewNetworkPanel.addTaskFactory(generateCustomStyleTaskFactory, propMap);
// Define listener
registerServiceListener(bc, createNewNetworkPanel, "addTaskFactory", "removeTaskFactory", TaskFactory.class);
// Export task
CyLayoutAlgorithmManager cyLayoutAlgorithmManager = getService(bc, CyLayoutAlgorithmManager.class);
final ApplySelectedLayoutTaskFactory applySelectedLayoutTaskFactory = new ApplySelectedLayoutTaskFactory(
registrar, applicationManager, cyLayoutAlgorithmManager);
Properties applySelectedLayoutTaskFactoryProps = new Properties();
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_ID, "applySelectedLayoutTaskFactory");
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_NAME, "Apply layout algorithm of your choice");
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_DESCRIPTION, "Apply a layout algorithm to the network.");
registerService(bc, applySelectedLayoutTaskFactory, TaskFactory.class, applySelectedLayoutTaskFactoryProps );
}
}
| src/main/java/org/cytoscape/welcome/internal/CyActivator.java | package org.cytoscape.welcome.internal;
import static org.cytoscape.work.ServiceProperties.IN_TOOL_BAR;
import static org.cytoscape.work.ServiceProperties.MENU_GRAVITY;
import static org.cytoscape.work.ServiceProperties.PREFERRED_MENU;
import static org.cytoscape.work.ServiceProperties.TITLE;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.cytoscape.application.CyApplicationConfiguration;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.CyVersion;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.io.datasource.DataSourceManager;
import org.cytoscape.io.util.RecentlyOpenedTracker;
import org.cytoscape.property.CyProperty;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.task.analyze.AnalyzeNetworkCollectionTaskFactory;
import org.cytoscape.task.read.LoadNetworkURLTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.visualize.ApplyPreferredLayoutTaskFactory;
import org.cytoscape.util.swing.OpenBrowser;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.presentation.property.values.BendFactory;
import org.cytoscape.view.vizmap.VisualMappingFunctionFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.welcome.internal.panel.CreateNewNetworkPanel;
import org.cytoscape.welcome.internal.panel.NewsAndLinkPanel;
import org.cytoscape.welcome.internal.panel.OpenPanel;
import org.cytoscape.welcome.internal.panel.StatusPanel;
import org.cytoscape.welcome.internal.task.ApplySelectedLayoutTaskFactory;
import org.cytoscape.welcome.internal.task.GenerateCustomStyleTaskFactory;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.swing.DialogTaskManager;
import org.osgi.framework.BundleContext;
public class CyActivator extends AbstractCyActivator {
public CyActivator() {
super();
}
public void start(BundleContext bc) {
final CyServiceRegistrar registrar = getService(bc, CyServiceRegistrar.class);
CyApplicationManager applicationManager = getService(bc, CyApplicationManager.class);
CyVersion cyVersion = getService(bc, CyVersion.class);
final ApplyPreferredLayoutTaskFactory applyPreferredLayoutTaskFactory = getService(bc,
ApplyPreferredLayoutTaskFactory.class);
BendFactory bendFactory = getService(bc, BendFactory.class);
VisualMappingManager vmm = getService(bc, VisualMappingManager.class);
VisualStyleFactory vsFactoryServiceRef = getService(bc, VisualStyleFactory.class);
VisualMappingFunctionFactory continupousMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=continuous)");
VisualMappingFunctionFactory passthroughMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=passthrough)");
VisualMappingFunctionFactory discreteMappingFactoryRef = getService(bc, VisualMappingFunctionFactory.class,
"(mapping.type=discrete)");
VisualStyleBuilder vsBuilder = new VisualStyleBuilder(vsFactoryServiceRef, continupousMappingFactoryRef,
discreteMappingFactoryRef, passthroughMappingFactoryRef, bendFactory);
AnalyzeNetworkCollectionTaskFactory analyzeNetworkCollectionTaskFactory = getService(bc,
AnalyzeNetworkCollectionTaskFactory.class);
CySwingApplication cytoscapeDesktop = getService(bc, CySwingApplication.class);
OpenBrowser openBrowserServiceRef = getService(bc, OpenBrowser.class);
RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc, RecentlyOpenedTracker.class);
OpenSessionTaskFactory openSessionTaskFactory = getService(bc, OpenSessionTaskFactory.class);
DialogTaskManager dialogTaskManagerServiceRef = getService(bc, DialogTaskManager.class);
TaskFactory importNetworkFileTF = getService(bc, TaskFactory.class, "(id=loadNetworkFileTaskFactory)");
LoadNetworkURLTaskFactory importNetworkTF = getService(bc, LoadNetworkURLTaskFactory.class);
CyApplicationConfiguration cyApplicationConfigurationServiceRef = getService(bc,
CyApplicationConfiguration.class);
DataSourceManager dsManagerServiceRef = getService(bc, DataSourceManager.class);
@SuppressWarnings("unchecked")
CyProperty<Properties> cytoscapePropertiesServiceRef = getService(bc, CyProperty.class,
"(cyPropertyName=cytoscape3.props)");
// Build Child Panels
final OpenPanel openPanel = new OpenPanel(recentlyOpenedTrackerServiceRef, dialogTaskManagerServiceRef,
openSessionTaskFactory);
final CreateNewNetworkPanel createNewNetworkPanel = new CreateNewNetworkPanel(bc, dialogTaskManagerServiceRef,
importNetworkFileTF, importNetworkTF, dsManagerServiceRef);
registerAllServices(bc, createNewNetworkPanel, new Properties());
// TODO: implement contents
final StatusPanel statusPanel = new StatusPanel(cyVersion);
final NewsAndLinkPanel helpPanel = new NewsAndLinkPanel(statusPanel, openBrowserServiceRef,
cytoscapePropertiesServiceRef);
// Show Welcome Screen
final WelcomeScreenAction welcomeScreenAction = new WelcomeScreenAction(createNewNetworkPanel, openPanel,
helpPanel, cytoscapePropertiesServiceRef, cytoscapeDesktop);
registerAllServices(bc, welcomeScreenAction, new Properties());
// Export preset tasks
final GenerateCustomStyleTaskFactory generateCustomStyleTaskFactory = new GenerateCustomStyleTaskFactory(
analyzeNetworkCollectionTaskFactory, applicationManager, vsBuilder, vmm);
Properties generateCustomStyleTaskFactoryProps = new Properties();
generateCustomStyleTaskFactoryProps.setProperty(PREFERRED_MENU, "Tools.Workflow");
generateCustomStyleTaskFactoryProps.setProperty(MENU_GRAVITY, "20.0");
generateCustomStyleTaskFactoryProps.setProperty(TITLE,
"Analyze selected networks and create custom Visual Styles");
generateCustomStyleTaskFactoryProps.setProperty(IN_TOOL_BAR, "false");
registerAllServices(bc, generateCustomStyleTaskFactory, generateCustomStyleTaskFactoryProps);
// This is a preset task, so register it first.
final Map<String, String> propMap = new HashMap<String, String>();
propMap.put(CreateNewNetworkPanel.WORKFLOW_ID, "generateCustomStyleTaskFactory");
propMap.put(CreateNewNetworkPanel.WORKFLOW_NAME, "Analyze network and create custom Visual Style");
propMap.put(CreateNewNetworkPanel.WORKFLOW_DESCRIPTION,
"Analyze current/selected networks and create custom Visual Style for each network.");
createNewNetworkPanel.addTaskFactory(generateCustomStyleTaskFactory, propMap);
// Define listener
registerServiceListener(bc, createNewNetworkPanel, "addTaskFactory", "removeTaskFactory", TaskFactory.class);
// Export task
CyLayoutAlgorithmManager cyLayoutAlgorithmManager = getService(bc, CyLayoutAlgorithmManager.class);
final ApplySelectedLayoutTaskFactory applySelectedLayoutTaskFactory = new ApplySelectedLayoutTaskFactory(
registrar, applicationManager, cyLayoutAlgorithmManager);
Properties applySelectedLayoutTaskFactoryProps = new Properties();
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_ID, "applySelectedLayoutTaskFactory");
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_NAME, "Apply layout algorithm of your choice");
applySelectedLayoutTaskFactoryProps.setProperty(CreateNewNetworkPanel.WORKFLOW_DESCRIPTION, "Apply a layout algorithm to the network.");
registerService(bc, applySelectedLayoutTaskFactory, TaskFactory.class, applySelectedLayoutTaskFactoryProps );
}
}
| fixes #1393 The workflow will be enabled only when view is available.
| src/main/java/org/cytoscape/welcome/internal/CyActivator.java | fixes #1393 The workflow will be enabled only when view is available. | <ide><path>rc/main/java/org/cytoscape/welcome/internal/CyActivator.java
<ide> import org.cytoscape.welcome.internal.panel.StatusPanel;
<ide> import org.cytoscape.welcome.internal.task.ApplySelectedLayoutTaskFactory;
<ide> import org.cytoscape.welcome.internal.task.GenerateCustomStyleTaskFactory;
<add>import org.cytoscape.work.ServiceProperties;
<ide> import org.cytoscape.work.TaskFactory;
<ide> import org.cytoscape.work.swing.DialogTaskManager;
<ide> import org.osgi.framework.BundleContext;
<ide> generateCustomStyleTaskFactoryProps.setProperty(TITLE,
<ide> "Analyze selected networks and create custom Visual Styles");
<ide> generateCustomStyleTaskFactoryProps.setProperty(IN_TOOL_BAR, "false");
<add> generateCustomStyleTaskFactoryProps.setProperty(ServiceProperties.ENABLE_FOR, "networkAndView");
<ide> registerAllServices(bc, generateCustomStyleTaskFactory, generateCustomStyleTaskFactoryProps);
<ide>
<ide> // This is a preset task, so register it first. |
|
JavaScript | mit | a4d94b098ec9152a21852500e84a45dedf82e570 | 0 | tomoyamkung/googlemap-sample | var InfoWindowStock = function() {
this.stock = [];
};
InfoWindowStock.prototype = {
createKey: function(location) {
var key = location.k + ":" + location.A;
return key;
},
put: function(location, infoWindow) {
var key = this.createKey(location);
this.stock[key] = infoWindow;
},
get: function(location) {
var key = this.createKey(location);
return this.stock[key];
}
};
/**
* 表示中の InfoWindow オブジェクト。
*/
var currentInfoWindow;
var stock = new InfoWindowStock();
$(function() {
var geocoder = new google.maps.Geocoder();
// 初期表示
var address = $('#address').val();
geocoder.geocode({'address': address}, callbackRender);
// 住所が入力された場合の対応
$('#address').change(function(event) {
address = $(this).val();
geocoder.geocode({'address': address}, callbackRender);
});
});
/**
* ジオコーダの結果を取得したときに実行するコールバック関数。
*
* この関数内で GoogleMap を出力する。
*
* @param results ジオコーダの結果
* @param status ジオコーディングのステータス
*
*/
function callbackRender(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 18,
center: results[0].geometry.location, // 指定の住所から計算した緯度経度を指定する
mapTypeId: google.maps.MapTypeId.ROADMAP // 「地図」で GoogleMap を出力する
};
var gmap = new google.maps.Map(document.getElementById('map-canvas'), options);
// #map-canvas に GoogleMap を出力する
setupMarker(gmap, results[0].geometry.location);
// 初期値の住所から計算した緯度経度の位置に Marker を立てる
google.maps.event.addListener(gmap, 'click', function(event) {
// GoogleMap 上で左クリックがあったら、、、
setupMarker(gmap, event.latLng);
// その場所に Marker を立てる
});
adjustMapSize();
}
}
/**
* 指定の場所に InfoWindow を設定した Marker を表示する。
*
* @param {Object} map Marker を立てる GoogleMap オブジェクト
* @param {Object} location Marker を立てる位置
*/
function setupMarker(map, location) {
var marker = new google.maps.Marker({map: map, position: location}); // Marker オブジェクトを生成する
this.disableCurrentInfoWindow();
currentInfoWindow = createInfoWindow(location.k, location.A); // InfoWindow オブジェクトを生成し、、、
currentInfoWindow.open(marker.getMap(), marker); // InfoWindow を表示する
// google.maps.event.addListener(marker, 'click', function(event) {
// console.log(event);
// });
}
/**
* 表示中の InfoWindow があれば非表示にする。
*
*/
function disableCurrentInfoWindow () {
if(this.currentInfoWindow) {
this.currentInfoWindow.close();
}
}
/**
* InfoWindow オブジェクトを生成する。
*
* @param {Number} latitude 緯度
* @param {Number} longitude 経度
* @return {Object} InfoWindow オブジェクト
*/
function createInfoWindow(latitude, longitude) {
var infoWindow = new google.maps.InfoWindow({
content: createTag(latitude, longitude), // InfoWindow に表示するコンテンツ
// maxWidth: 1000 // width は CSS で制御するようにしたのでコメントアウト
});
return infoWindow;
}
/**
* InfoWindow 内に設定する HTML を生成する。
*
* HTML の生成は Underscore.js を使い、テンプレートは index.html 内に定義してある。
*
* @param {Number} latitude 緯度
* @param {Number} longitude 経度
* @return {Object} InfoWindow に設定するタグ
*/
function createTag(latitude, longitude) {
var template = _.template($('#infowindow_template').text());
var tag = template({latitude: latitude, longitude: longitude});
return tag;
}
/**
* GoogleMap を表示する div タグのサイズを調整する。
*
*/
function adjustMapSize() {
var padding = $('#header-hollow').height(); // 住所入力欄の height を取得
var mapCanvas = $('#map-canvas');
mapCanvas.css("height", ($(window).height() - mapCanvas.offset().top) - padding + "px");
}
| js/script.js | /**
* 表示中の InfoWindow オブジェクト。
*/
var currentInfoWindow;
var stock = new InfoWindowStock();
$(function() {
var geocoder = new google.maps.Geocoder();
// 初期表示
var address = $('#address').val();
geocoder.geocode({'address': address}, callbackRender);
// 住所が入力された場合の対応
$('#address').change(function(event) {
address = $(this).val();
geocoder.geocode({'address': address}, callbackRender);
});
});
/**
* ジオコーダの結果を取得したときに実行するコールバック関数。
*
* この関数内で GoogleMap を出力する。
*
* @param results ジオコーダの結果
* @param status ジオコーディングのステータス
*
*/
function callbackRender(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 18,
center: results[0].geometry.location, // 指定の住所から計算した緯度経度を指定する
mapTypeId: google.maps.MapTypeId.ROADMAP // 「地図」で GoogleMap を出力する
};
var gmap = new google.maps.Map(document.getElementById('map-canvas'), options);
// #map-canvas に GoogleMap を出力する
setupMarker(gmap, results[0].geometry.location);
// 初期値の住所から計算した緯度経度の位置に Marker を立てる
google.maps.event.addListener(gmap, 'click', function(event) {
// GoogleMap 上で左クリックがあったら、、、
setupMarker(gmap, event.latLng);
// その場所に Marker を立てる
});
adjustMapSize();
}
}
/**
* 指定の場所に InfoWindow を設定した Marker を表示する。
*
* @param {Object} map Marker を立てる GoogleMap オブジェクト
* @param {Object} location Marker を立てる位置
*/
function setupMarker(map, location) {
var marker = new google.maps.Marker({map: map, position: location}); // Marker オブジェクトを生成する
currentInfoWindow = createInfoWindow(location.k, location.A); // InfoWindow オブジェクトを生成し、、、
currentInfoWindow.open(marker.getMap(), marker); // InfoWindow を表示する
}
/**
* InfoWindow オブジェクトを生成する。
*
* @param {Number} latitude 緯度
* @param {Number} longitude 経度
* @return {Object} InfoWindow オブジェクト
*/
function createInfoWindow(latitude, longitude) {
var infoWindow = new google.maps.InfoWindow({
content: createTag(latitude, longitude), // InfoWindow に表示するコンテンツ
// maxWidth: 1000 // width は CSS で制御するようにしたのでコメントアウト
});
return infoWindow;
}
/**
* InfoWindow 内に設定する HTML を生成する。
*
* HTML の生成は Underscore.js を使い、テンプレートは index.html 内に定義してある。
*
* @param {Number} latitude 緯度
* @param {Number} longitude 経度
* @return {Object} InfoWindow に設定するタグ
*/
function createTag(latitude, longitude) {
var template = _.template($('#infowindow_template').text());
var tag = template({latitude: latitude, longitude: longitude});
return tag;
}
/**
* GoogleMap を表示する div タグのサイズを調整する。
*
*/
function adjustMapSize() {
var padding = $('#header-hollow').height(); // 住所入力欄の height を取得
var mapCanvas = $('#map-canvas');
mapCanvas.css("height", ($(window).height() - mapCanvas.offset().top) - padding + "px");
}
var InfoWindowStock = function() {
this.stock = [];
};
InfoWindowStock.prototype.createKey = function(location) {
var key = location.k + ":" + location.A;
return key;
};
InfoWindowStock.prototype.put = function(location, infoWindow) {
var key = this.createKey(location);
this.stock[key] = infoWindow;
};
InfoWindowStock.prototype.get = function(location) {
var key = this.createKey(location);
return this.stock[key];
};
| 最新の InfoWindow のみを表示するように変更したのでコミット。
| js/script.js | 最新の InfoWindow のみを表示するように変更したのでコミット。 | <ide><path>s/script.js
<add>var InfoWindowStock = function() {
<add> this.stock = [];
<add>};
<add>InfoWindowStock.prototype = {
<add> createKey: function(location) {
<add> var key = location.k + ":" + location.A;
<add> return key;
<add> },
<add> put: function(location, infoWindow) {
<add> var key = this.createKey(location);
<add> this.stock[key] = infoWindow;
<add> },
<add> get: function(location) {
<add> var key = this.createKey(location);
<add> return this.stock[key];
<add> }
<add>};
<add>
<ide> /**
<ide> * 表示中の InfoWindow オブジェクト。
<ide> */
<ide> function setupMarker(map, location) {
<ide> var marker = new google.maps.Marker({map: map, position: location}); // Marker オブジェクトを生成する
<ide>
<add> this.disableCurrentInfoWindow();
<add>
<ide> currentInfoWindow = createInfoWindow(location.k, location.A); // InfoWindow オブジェクトを生成し、、、
<ide> currentInfoWindow.open(marker.getMap(), marker); // InfoWindow を表示する
<add>
<add> // google.maps.event.addListener(marker, 'click', function(event) {
<add> // console.log(event);
<add> // });
<ide> }
<ide>
<add>/**
<add> * 表示中の InfoWindow があれば非表示にする。
<add> *
<add> */
<add>function disableCurrentInfoWindow () {
<add> if(this.currentInfoWindow) {
<add> this.currentInfoWindow.close();
<add> }
<add>}
<ide>
<ide> /**
<ide> * InfoWindow オブジェクトを生成する。
<ide> mapCanvas.css("height", ($(window).height() - mapCanvas.offset().top) - padding + "px");
<ide> }
<ide>
<del>var InfoWindowStock = function() {
<del> this.stock = [];
<del>};
<del>InfoWindowStock.prototype.createKey = function(location) {
<del> var key = location.k + ":" + location.A;
<del> return key;
<del>};
<del>InfoWindowStock.prototype.put = function(location, infoWindow) {
<del> var key = this.createKey(location);
<del> this.stock[key] = infoWindow;
<del>};
<del>InfoWindowStock.prototype.get = function(location) {
<del> var key = this.createKey(location);
<del> return this.stock[key];
<del>}; |
|
Java | mit | e53c81aad028b961aa09e3379a8613460ac563e4 | 0 | way2muchnoise/fontbox,AfterLifeLochie/fontbox | package net.afterlifelochie.fontbox;
import java.io.IOException;
import java.util.ArrayList;
import net.afterlifelochie.io.StackedPushbackStringReader;
public class LayoutCalculator {
/**
* Attempt to box a line or part of a line onto a PageBox. This immediately
* attempts to fit as much of the line onto a LineBox and then glues it to
* the tail of a PageBox if the PageBox can support the addition of a line.
* Any overflow text which cannot be boxed onto the page is returned.
*
* @param metric
* The font metric to calculate with
* @param line
* The line
* @param page
* The page to box onto
* @return If a page overflow occurs - that is, if there is no more
* available vertical space for lines to occupy.
*/
public boolean boxLine(FontMetric metric, StackedPushbackStringReader text,
PageBox page) throws IOException {
// Calculate some required properties
int effectiveWidth = page.page_width - page.margin_left
- page.margin_right;
int effectiveHeight = page.getFreeHeight();
int width_new_line = 0, width_new_word = 0;
// Start globbing characters
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
// Push our place in case we have to abort
text.pushPosition();
while (text.available() > 0) {
// Take a char
char c = text.next();
// Treat space as a word separator
if (c == '\r' || c == '\n') {
// Look and see if the next character is a newline
char c1 = text.next();
if (c1 != '\n' && c1 != '\r')
text.rewind(1); // put it back, aha!
break; // hard eol
} else if (c == ' ') {
// Push a whole word if one exists
if (chars.size() > 0) {
// Find out if there is enough space to push this word
int new_width_nl = width_new_line + width_new_word
+ page.min_space_size;
if (effectiveWidth >= new_width_nl) {
// Yes, there is enough space, add the word
width_new_line += width_new_word;
StringBuilder builder = new StringBuilder();
for (char c1 : chars)
builder.append(c1);
words.add(builder.toString());
// Clear the character buffers
chars.clear();
width_new_word = 0;
} else {
// No, the word doesn't fit, back it up
text.rewind(chars.size()+1);
chars.clear();
width_new_word = 0;
break;
}
}
} else {
GlyphMetric mx = metric.glyphs.get((int) c);
if (mx != null) {
width_new_word += mx.width;
chars.add(c);
}
}
}
// Anything left on buffer?
if (chars.size() > 0) {
// Find out if there is enough space to push this word
int new_width_nl = width_new_line + width_new_word
+ page.min_space_size;
if (effectiveWidth >= new_width_nl) {
// Yes, there is enough space, add the word
width_new_line += width_new_word;
StringBuilder builder = new StringBuilder();
for (char c1 : chars)
builder.append(c1);
words.add(builder.toString());
// Clear the character buffers
chars.clear();
width_new_word = 0;
} else {
// No, the word doesn't fit, back it up
chars.clear();
}
}
// Find the maximum height of any characters in the line
int height_new_line = page.lineheight_size;
for (int i = 0; i < words.size(); i++) {
String word = words.get(i);
for (int j = 0; j < word.length(); j++) {
char c = word.charAt(j);
if (c != ' ') {
GlyphMetric mx = metric.glyphs.get((int) c);
if (mx.height > height_new_line)
height_new_line = mx.height;
}
}
}
// If the line doesn't fit at all, we can't do anything
if (height_new_line > effectiveHeight) {
text.popPosition(); // back out
return true;
}
// Commit our position as we have now read a line and it fits all
// current constraints on the page
text.commitPosition();
// Glue the whole line together
StringBuilder line = new StringBuilder();
for (int i = 0; i < words.size(); i++) {
line.append(words.get(i));
if (i != words.size() - 1)
line.append(" ");
}
// Figure out how much space is left over from the line
int space_remain = effectiveWidth - width_new_line;
int space_width = page.min_space_size;
// If the line is not blank, then...
if (words.size() > 0) {
int extra_px_per_space = (int) Math.floor(space_remain
/ words.size());
if (width_new_line > extra_px_per_space)
space_width = page.min_space_size + extra_px_per_space;
} else
height_new_line = 2 * page.lineheight_size;
// Make the line height fit exactly 1 or more line units
int line_height = height_new_line;
if (line_height % page.lineheight_size != 0) {
line_height -= line_height % page.lineheight_size;
// line_height += page.lineheight_size;
}
// Create the linebox
page.lines.add(new LineBox(line.toString(), space_width, line_height));
return false;
}
/**
* Attempt to box a paragraph or part of a paragraph onto a collection of
* PageBox instances.
*
* @param metric
* The font metric to calculate with
* @param text
* The text blob
* @return The page results
*/
public PageBox[] boxParagraph(FontMetric metric, String text, int width,
int height, int margin_l, int margin_r, int min_sp, int min_lhs)
throws IOException {
StackedPushbackStringReader reader = new StackedPushbackStringReader(
text);
ArrayList<PageBox> pages = new ArrayList<PageBox>();
PageBox currentPage = new PageBox(width, height, margin_l, margin_r,
min_sp, min_lhs);
boolean flag = false;
while (reader.available() > 0) {
flag = boxLine(metric, reader, currentPage);
if (flag) {
pages.add(currentPage);
currentPage = new PageBox(width, height, margin_l, margin_r,
min_sp, min_lhs);
}
}
if (!flag)
pages.add(currentPage);
return pages.toArray(new PageBox[0]);
}
}
| src/main/java/net/afterlifelochie/fontbox/LayoutCalculator.java | package net.afterlifelochie.fontbox;
import java.io.IOException;
import java.util.ArrayList;
import net.afterlifelochie.io.StackedPushbackStringReader;
public class LayoutCalculator {
/**
* Attempt to box a line or part of a line onto a PageBox. This immediately
* attempts to fit as much of the line onto a LineBox and then glues it to
* the tail of a PageBox if the PageBox can support the addition of a line.
* Any overflow text which cannot be boxed onto the page is returned.
*
* @param metric
* The font metric to calculate with
* @param line
* The line
* @param page
* The page to box onto
* @return If a page overflow occurs - that is, if there is no more
* available vertical space for lines to occupy.
*/
public boolean boxLine(FontMetric metric, StackedPushbackStringReader text,
PageBox page) throws IOException {
// Calculate some required properties
int effectiveWidth = page.page_width - page.margin_left
- page.margin_right;
int effectiveHeight = page.getFreeHeight();
int width_new_line = 0, width_new_word = 0;
// Start globbing characters
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
// Push our place in case we have to abort
text.pushPosition();
while (text.available() > 0) {
// Take a char
char c = text.next();
// Treat space as a word separator
if (c == '\r' || c == '\n') {
// Look and see if the next character is a newline
char c1 = text.next();
if (c1 != '\n' && c1 != '\r')
text.rewind(1); // put it back, aha!
break; // hard eol
} else if (c == ' ') {
// Push a whole word if one exists
if (chars.size() > 0) {
// Find out if there is enough space to push this word
int new_width_nl = width_new_line + width_new_word
+ page.min_space_size;
if (effectiveWidth >= new_width_nl) {
// Yes, there is enough space, add the word
width_new_line += width_new_word;
StringBuilder builder = new StringBuilder();
for (char c1 : chars)
builder.append(c1);
words.add(builder.toString());
// Clear the character buffers
chars.clear();
width_new_word = 0;
} else {
// No, the word doesn't fit, back it up
chars.clear();
width_new_word = 0;
break;
}
}
} else {
GlyphMetric mx = metric.glyphs.get((int) c);
if (mx != null) {
width_new_word += mx.width;
chars.add(c);
}
}
}
// Anything left on buffer?
if (chars.size() > 0) {
// Find out if there is enough space to push this word
int new_width_nl = width_new_line + width_new_word
+ page.min_space_size;
if (effectiveWidth >= new_width_nl) {
// Yes, there is enough space, add the word
width_new_line += width_new_word;
StringBuilder builder = new StringBuilder();
for (char c1 : chars)
builder.append(c1);
words.add(builder.toString());
// Clear the character buffers
chars.clear();
width_new_word = 0;
} else {
// No, the word doesn't fit, back it up
chars.clear();
}
}
// Find the maximum height of any characters in the line
int height_new_line = page.lineheight_size;
for (int i = 0; i < words.size(); i++) {
String word = words.get(i);
for (int j = 0; j < word.length(); j++) {
char c = word.charAt(j);
if (c != ' ') {
GlyphMetric mx = metric.glyphs.get((int) c);
if (mx.height > height_new_line)
height_new_line = mx.height;
}
}
}
// If the line doesn't fit at all, we can't do anything
if (height_new_line > effectiveHeight) {
text.popPosition(); // back out
return true;
}
// Commit our position as we have now read a line and it fits all
// current constraints on the page
text.commitPosition();
// Glue the whole line together
StringBuilder line = new StringBuilder();
for (int i = 0; i < words.size(); i++) {
line.append(words.get(i));
if (i != words.size() - 1)
line.append(" ");
}
// Figure out how much space is left over from the line
int space_remain = effectiveWidth - width_new_line;
int space_width = page.min_space_size;
// If the line is not blank, then...
if (words.size() > 0) {
int extra_px_per_space = (int) Math.floor(space_remain
/ words.size());
if (width_new_line > extra_px_per_space)
space_width = page.min_space_size + extra_px_per_space;
} else
height_new_line = 2 * page.lineheight_size;
// Make the line height fit exactly 1 or more line units
int line_height = height_new_line;
if (line_height % page.lineheight_size != 0) {
line_height -= line_height % page.lineheight_size;
// line_height += page.lineheight_size;
}
// Create the linebox
page.lines.add(new LineBox(line.toString(), space_width, line_height));
return false;
}
/**
* Attempt to box a paragraph or part of a paragraph onto a collection of
* PageBox instances.
*
* @param metric
* The font metric to calculate with
* @param text
* The text blob
* @return The page results
*/
public PageBox[] boxParagraph(FontMetric metric, String text, int width,
int height, int margin_l, int margin_r, int min_sp, int min_lhs)
throws IOException {
StackedPushbackStringReader reader = new StackedPushbackStringReader(
text);
ArrayList<PageBox> pages = new ArrayList<PageBox>();
PageBox currentPage = new PageBox(width, height, margin_l, margin_r,
min_sp, min_lhs);
boolean flag = false;
while (reader.available() > 0) {
flag = boxLine(metric, reader, currentPage);
if (flag) {
pages.add(currentPage);
currentPage = new PageBox(width, height, margin_l, margin_r,
min_sp, min_lhs);
}
}
if (!flag)
pages.add(currentPage);
return pages.toArray(new PageBox[0]);
}
}
| Fixes LayoutCalculator.boxLine
Actually back up the word in the StackedPushbackStringReader. Just commenting it doesn't cut it :p | src/main/java/net/afterlifelochie/fontbox/LayoutCalculator.java | Fixes LayoutCalculator.boxLine | <ide><path>rc/main/java/net/afterlifelochie/fontbox/LayoutCalculator.java
<ide> width_new_word = 0;
<ide> } else {
<ide> // No, the word doesn't fit, back it up
<add> text.rewind(chars.size()+1);
<ide> chars.clear();
<ide> width_new_word = 0;
<ide> break; |
|
Java | apache-2.0 | cd67a7e2bf434ec3eb2c631e76199abf2e4d3c5e | 0 | m2049r/xmrwallet,m2049r/xmrwallet,m2049r/xmrwallet | /*
* Copyright (c) 2018 m2049r
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.m2049r.xmrwallet.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class RestoreHeight {
static private RestoreHeight Singleton = null;
static public RestoreHeight getInstance() {
if (Singleton == null) {
synchronized (RestoreHeight.class) {
if (Singleton == null) {
Singleton = new RestoreHeight();
}
}
}
return Singleton;
}
private Map<String, Long> blockheight = new HashMap<>();
RestoreHeight() {
blockheight.put("2014-05-01", 18844L);
blockheight.put("2014-06-01", 65406L);
blockheight.put("2014-07-01", 108882L);
blockheight.put("2014-08-01", 153594L);
blockheight.put("2014-09-01", 198072L);
blockheight.put("2014-10-01", 241088L);
blockheight.put("2014-11-01", 285305L);
blockheight.put("2014-12-01", 328069L);
blockheight.put("2015-01-01", 372369L);
blockheight.put("2015-02-01", 416505L);
blockheight.put("2015-03-01", 456631L);
blockheight.put("2015-04-01", 501084L);
blockheight.put("2015-05-01", 543973L);
blockheight.put("2015-06-01", 588326L);
blockheight.put("2015-07-01", 631187L);
blockheight.put("2015-08-01", 675484L);
blockheight.put("2015-09-01", 719725L);
blockheight.put("2015-10-01", 762463L);
blockheight.put("2015-11-01", 806528L);
blockheight.put("2015-12-01", 849041L);
blockheight.put("2016-01-01", 892866L);
blockheight.put("2016-02-01", 936736L);
blockheight.put("2016-03-01", 977691L);
blockheight.put("2016-04-01", 1015848L);
blockheight.put("2016-05-01", 1037417L);
blockheight.put("2016-06-01", 1059651L);
blockheight.put("2016-07-01", 1081269L);
blockheight.put("2016-08-01", 1103630L);
blockheight.put("2016-09-01", 1125983L);
blockheight.put("2016-10-01", 1147617L);
blockheight.put("2016-11-01", 1169779L);
blockheight.put("2016-12-01", 1191402L);
blockheight.put("2017-01-01", 1213861L);
blockheight.put("2017-02-01", 1236197L);
blockheight.put("2017-03-01", 1256358L);
blockheight.put("2017-04-01", 1278622L);
blockheight.put("2017-05-01", 1300239L);
blockheight.put("2017-06-01", 1322564L);
blockheight.put("2017-07-01", 1344225L);
blockheight.put("2017-08-01", 1366664L);
blockheight.put("2017-09-01", 1389113L);
blockheight.put("2017-10-01", 1410738L);
blockheight.put("2017-11-01", 1433039L);
blockheight.put("2017-12-01", 1454639L);
blockheight.put("2018-01-01", 1477201L);
blockheight.put("2018-02-01", 1499599L);
blockheight.put("2018-03-01", 1519796L);
blockheight.put("2018-04-01", 1542067L);
blockheight.put("2018-05-01", 1562861L);
blockheight.put("2018-06-01", 1585135L);
blockheight.put("2018-07-01", 1606715L);
blockheight.put("2018-08-01", 1629017L);
blockheight.put("2018-09-01", 1651347L);
blockheight.put("2018-10-01", 1673031L);
blockheight.put("2018-11-01", 1695128L);
blockheight.put("2018-12-01", 1716687L);
blockheight.put("2019-01-01", 1738923L);
blockheight.put("2019-02-01", 1761435L);
}
public long getHeight(String date) {
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
parser.setLenient(false);
try {
return getHeight(parser.parse(date));
} catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
public long getHeight(final Date date) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.DST_OFFSET, 0);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -4); // give it some leeway
if (cal.get(Calendar.YEAR) < 2014)
return 0;
if ((cal.get(Calendar.YEAR) == 2014) && (cal.get(Calendar.MONTH) <= 3))
// before May 2014
return 0;
Calendar query = (Calendar) cal.clone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String queryDate = formatter.format(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
long prevTime = cal.getTimeInMillis();
String prevDate = formatter.format(prevTime);
// lookup blockheight at first of the month
Long prevBc = blockheight.get(prevDate);
if (prevBc == null) {
// if too recent, go back in time and find latest one we have
while (prevBc == null) {
cal.add(Calendar.MONTH, -1);
if (cal.get(Calendar.YEAR) < 2014) {
throw new IllegalStateException("endless loop looking for blockheight");
}
prevTime = cal.getTimeInMillis();
prevDate = formatter.format(prevTime);
prevBc = blockheight.get(prevDate);
}
}
long height = prevBc;
// now we have a blockheight & a date ON or BEFORE the restore date requested
if (queryDate.equals(prevDate)) return height;
// see if we have a blockheight after this date
cal.add(Calendar.MONTH, 1);
long nextTime = cal.getTimeInMillis();
String nextDate = formatter.format(nextTime);
Long nextBc = blockheight.get(nextDate);
if (nextBc != null) { // we have a range - interpolate the blockheight we are looking for
long diff = nextBc - prevBc;
long diffDays = TimeUnit.DAYS.convert(nextTime - prevTime, TimeUnit.MILLISECONDS);
long days = TimeUnit.DAYS.convert(query.getTimeInMillis() - prevTime,
TimeUnit.MILLISECONDS);
height = Math.round(prevBc + diff * (1.0 * days / diffDays));
} else {
long days = TimeUnit.DAYS.convert(query.getTimeInMillis() - prevTime,
TimeUnit.MILLISECONDS);
height = Math.round(prevBc + 1.0 * days * (24 * 60 / 2));
}
return height;
}
}
| app/src/main/java/com/m2049r/xmrwallet/util/RestoreHeight.java | /*
* Copyright (c) 2018 m2049r
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.m2049r.xmrwallet.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class RestoreHeight {
static private RestoreHeight Singleton = null;
static public RestoreHeight getInstance() {
if (Singleton == null) {
synchronized (RestoreHeight.class) {
if (Singleton == null) {
Singleton = new RestoreHeight();
}
}
}
return Singleton;
}
private Map<String, Long> blockheight = new HashMap<>();
RestoreHeight() {
blockheight.put("2014-05-01", 18844L);
blockheight.put("2014-06-01", 65406L);
blockheight.put("2014-07-01", 108882L);
blockheight.put("2014-08-01", 153594L);
blockheight.put("2014-09-01", 198072L);
blockheight.put("2014-10-01", 241088L);
blockheight.put("2014-11-01", 285305L);
blockheight.put("2014-12-01", 328069L);
blockheight.put("2015-01-01", 372369L);
blockheight.put("2015-02-01", 416505L);
blockheight.put("2015-03-01", 456631L);
blockheight.put("2015-04-01", 501084L);
blockheight.put("2015-05-01", 543973L);
blockheight.put("2015-06-01", 588326L);
blockheight.put("2015-07-01", 631187L);
blockheight.put("2015-08-01", 675484L);
blockheight.put("2015-09-01", 719725L);
blockheight.put("2015-10-01", 762463L);
blockheight.put("2015-11-01", 806528L);
blockheight.put("2015-12-01", 849041L);
blockheight.put("2016-01-01", 892866L);
blockheight.put("2016-02-01", 936736L);
blockheight.put("2016-03-01", 977691L);
blockheight.put("2016-04-01", 1015848L);
blockheight.put("2016-05-01", 1037417L);
blockheight.put("2016-06-01", 1059651L);
blockheight.put("2016-07-01", 1081269L);
blockheight.put("2016-08-01", 1103630L);
blockheight.put("2016-09-01", 1125983L);
blockheight.put("2016-10-01", 1147617L);
blockheight.put("2016-11-01", 1169779L);
blockheight.put("2016-12-01", 1191402L);
blockheight.put("2017-01-01", 1213861L);
blockheight.put("2017-02-01", 1236197L);
blockheight.put("2017-03-01", 1256358L);
blockheight.put("2017-04-01", 1278622L);
blockheight.put("2017-05-01", 1300239L);
blockheight.put("2017-06-01", 1322564L);
blockheight.put("2017-07-01", 1344225L);
blockheight.put("2017-08-01", 1366664L);
blockheight.put("2017-09-01", 1389113L);
blockheight.put("2017-10-01", 1410738L);
blockheight.put("2017-11-01", 1433039L);
blockheight.put("2017-12-01", 1454639L);
blockheight.put("2018-01-01", 1477201L);
blockheight.put("2018-02-01", 1499599L);
blockheight.put("2018-03-01", 1519796L);
blockheight.put("2018-04-01", 1542067L);
blockheight.put("2018-05-01", 1562861L);
blockheight.put("2018-06-01", 1585135L);
blockheight.put("2018-07-01", 1606715L);
blockheight.put("2018-08-01", 1629017L);
blockheight.put("2018-09-01", 1651347L);
blockheight.put("2018-10-01", 1673031L);
blockheight.put("2018-11-01", 1695128L);
blockheight.put("2018-12-01", 1716687L);
blockheight.put("2019-01-01", 1738923L);
}
public long getHeight(String date) {
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
parser.setLenient(false);
try {
return getHeight(parser.parse(date));
} catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
public long getHeight(final Date date) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.DST_OFFSET, 0);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -4); // give it some leeway
if (cal.get(Calendar.YEAR) < 2014)
return 0;
if ((cal.get(Calendar.YEAR) == 2014) && (cal.get(Calendar.MONTH) <= 3))
// before May 2014
return 0;
Calendar query = (Calendar) cal.clone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String queryDate = formatter.format(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
long prevTime = cal.getTimeInMillis();
String prevDate = formatter.format(prevTime);
// lookup blockheight at first of the month
Long prevBc = blockheight.get(prevDate);
if (prevBc == null) {
// if too recent, go back in time and find latest one we have
while (prevBc == null) {
cal.add(Calendar.MONTH, -1);
if (cal.get(Calendar.YEAR) < 2014) {
throw new IllegalStateException("endless loop looking for blockheight");
}
prevTime = cal.getTimeInMillis();
prevDate = formatter.format(prevTime);
prevBc = blockheight.get(prevDate);
}
}
long height = prevBc;
// now we have a blockheight & a date ON or BEFORE the restore date requested
if (queryDate.equals(prevDate)) return height;
// see if we have a blockheight after this date
cal.add(Calendar.MONTH, 1);
long nextTime = cal.getTimeInMillis();
String nextDate = formatter.format(nextTime);
Long nextBc = blockheight.get(nextDate);
if (nextBc != null) { // we have a range - interpolate the blockheight we are looking for
long diff = nextBc - prevBc;
long diffDays = TimeUnit.DAYS.convert(nextTime - prevTime, TimeUnit.MILLISECONDS);
long days = TimeUnit.DAYS.convert(query.getTimeInMillis() - prevTime,
TimeUnit.MILLISECONDS);
height = Math.round(prevBc + diff * (1.0 * days / diffDays));
} else {
long days = TimeUnit.DAYS.convert(query.getTimeInMillis() - prevTime,
TimeUnit.MILLISECONDS);
height = Math.round(prevBc + 1.0 * days * (24 * 60 / 2));
}
return height;
}
}
| 2019-02 height
| app/src/main/java/com/m2049r/xmrwallet/util/RestoreHeight.java | 2019-02 height | <ide><path>pp/src/main/java/com/m2049r/xmrwallet/util/RestoreHeight.java
<ide> blockheight.put("2018-11-01", 1695128L);
<ide> blockheight.put("2018-12-01", 1716687L);
<ide> blockheight.put("2019-01-01", 1738923L);
<add> blockheight.put("2019-02-01", 1761435L);
<ide> }
<ide>
<ide> public long getHeight(String date) { |
|
Java | apache-2.0 | d3dfea0a493c6f8879bd528b6d0785087d698d80 | 0 | jdereg/java-util | package com.cedarsoftware.util;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Utilities to simplify writing reflective code as well as improve performance of reflective operations like
* method and annotation lookups.
*
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public final class ReflectionUtils
{
private static final ConcurrentMap<Class<?>, Collection<Field>> FIELD_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Method> METHOD_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Method> METHOD_MAP2 = new ConcurrentHashMap<>();
private ReflectionUtils()
{
super();
}
/**
* Determine if the passed in class (classToCheck) has the annotation (annoClass) on itself,
* any of its super classes, any of it's interfaces, or any of it's super interfaces.
* This is a exhaustive check throughout the complete inheritance hierarchy.
* @return the Annotation if found, null otherwise.
*/
public static <T extends Annotation> T getClassAnnotation(final Class<?> classToCheck, final Class<T> annoClass)
{
final Set<Class<?>> visited = new HashSet<>();
final LinkedList<Class<?>> stack = new LinkedList<>();
stack.add(classToCheck);
while (!stack.isEmpty())
{
Class<?> classToChk = stack.pop();
if (classToChk == null || visited.contains(classToChk))
{
continue;
}
visited.add(classToChk);
T a = (T) classToChk.getAnnotation(annoClass);
if (a != null)
{
return a;
}
stack.push(classToChk.getSuperclass());
addInterfaces(classToChk, stack);
}
return null;
}
private static void addInterfaces(final Class<?> classToCheck, final LinkedList<Class<?>> stack)
{
for (Class<?> interFace : classToCheck.getInterfaces())
{
stack.push(interFace);
}
}
public static <T extends Annotation> T getMethodAnnotation(final Method method, final Class<T> annoClass)
{
final Set<Class<?>> visited = new HashSet<>();
final LinkedList<Class<?>> stack = new LinkedList<>();
stack.add(method.getDeclaringClass());
while (!stack.isEmpty())
{
Class<?> classToChk = stack.pop();
if (classToChk == null || visited.contains(classToChk))
{
continue;
}
visited.add(classToChk);
Method m = getMethod(classToChk, method.getName(), method.getParameterTypes());
if (m == null)
{
continue;
}
T a = m.getAnnotation(annoClass);
if (a != null)
{
return a;
}
stack.push(classToChk.getSuperclass());
addInterfaces(method.getDeclaringClass(), stack);
}
return null;
}
/**
* Fetch a public method reflectively by name with argument types. This method caches the lookup, so that
* subsequent calls are significantly faster. The method can be on an inherited class of the passed in [starting]
* Class.
* @param c Class on which method is to be found.
* @param methodName String name of method to find.
* @param types Argument types for the method (null is used for no argument methods).
* @return Method located, or null if not found.
*/
public static Method getMethod(Class<?> c, String methodName, Class<?>...types)
{
try
{
StringBuilder builder = new StringBuilder(c.getName());
builder.append('.');
builder.append(methodName);
for (Class clz : types)
{
builder.append('|');
builder.append(clz.getName());
}
// methodKey is in form ClassName.methodName|arg1.class|arg2.class|...
String methodKey = builder.toString();
Method method = METHOD_MAP.get(methodKey);
if (method == null)
{
method = c.getMethod(methodName, types);
Method other = METHOD_MAP.putIfAbsent(methodKey, method);
if (other != null)
{
method = other;
}
}
return method;
}
catch (Exception nse)
{
return null;
}
}
/**
* Get all non static, non transient, fields of the passed in class, including
* private fields. Note, the special this$ field is also not returned. The result
* is cached in a static ConcurrentHashMap to benefit execution performance.
* @param c Class instance
* @return Collection of only the fields in the passed in class
* that would need further processing (reference fields). This
* makes field traversal on a class faster as it does not need to
* continually process known fields like primitives.
*/
public static Collection<Field> getDeepDeclaredFields(Class<?> c)
{
if (FIELD_MAP.containsKey(c))
{
return FIELD_MAP.get(c);
}
Collection<Field> fields = new ArrayList<>();
Class<?> curr = c;
while (curr != null)
{
getDeclaredFields(curr, fields);
curr = curr.getSuperclass();
}
FIELD_MAP.put(c, fields);
return fields;
}
/**
* Get all non static, non transient, fields of the passed in class, including
* private fields. Note, the special this$ field is also not returned. The
* resulting fields are stored in a Collection.
* @param c Class instance
* that would need further processing (reference fields). This
* makes field traversal on a class faster as it does not need to
* continually process known fields like primitives.
*/
public static void getDeclaredFields(Class<?> c, Collection<Field> fields) {
try
{
Field[] local = c.getDeclaredFields();
for (Field field : local)
{
try
{
field.setAccessible(true);
}
catch (Exception ignored) { }
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) &&
!field.getName().startsWith("this$") &&
!Modifier.isTransient(modifiers))
{ // speed up: do not count static fields, do not go back up to enclosing object in nested case, do not consider transients
fields.add(field);
}
}
}
catch (Throwable ignored)
{
ExceptionUtilities.safelyIgnoreException(ignored);
}
}
/**
* Return all Fields from a class (including inherited), mapped by
* String field name to java.lang.reflect.Field.
* @param c Class whose fields are being fetched.
* @return Map of all fields on the Class, keyed by String field
* name to java.lang.reflect.Field.
*/
public static Map<String, Field> getDeepDeclaredFieldMap(Class<?> c)
{
Map<String, Field> fieldMap = new HashMap<>();
Collection<Field> fields = getDeepDeclaredFields(c);
for (Field field : fields)
{
String fieldName = field.getName();
if (fieldMap.containsKey(fieldName))
{ // Can happen when parent and child class both have private field with same name
fieldMap.put(field.getDeclaringClass().getName() + '.' + fieldName, field);
}
else
{
fieldMap.put(fieldName, field);
}
}
return fieldMap;
}
/**
* Make reflective method calls without having to handle two checked exceptions (IllegalAccessException and
* InvocationTargetException). These exceptions are caught and rethrown as RuntimeExceptions, with the original
* exception passed (nested) on.
* @param bean Object (instance) on which to call method.
* @param method Method instance from target object [easily obtained by calling ReflectionUtils.getMethod()].
* @param args Arguments to pass to method.
* @return Object Value from reflectively called method.
*/
public static Object call(Object bean, Method method, Object... args)
{
if (method == null)
{
String className = bean == null ? "null bean" : bean.getClass().getName();
throw new IllegalArgumentException("null Method passed to ReflectionUtils.call() on bean of type: " + className);
}
if (bean == null)
{
throw new IllegalArgumentException("Cannot call [" + method.getName() + "()] on a null object.");
}
try
{
return method.invoke(bean, args);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("IllegalAccessException occurred attempting to reflectively call method: " + method.getName() + "()", e);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Exception thrown inside reflectively called method: " + method.getName() + "()", e.getTargetException());
}
}
/**
* Make a reflective method call in one step. This approach does not support calling two different methods with
* the same argument count, since it caches methods internally by "className.methodName|argCount". For example,
* if you had a class with two methods, foo(int, String) and foo(String, String), you cannot use this method.
* However, this method would support calling foo(int), foo(int, String), foo(int, String, Object), etc.
* Internally, it is caching the reflective method lookups as mentioned earlier for speed, using argument count
* as part of the key (not all argument types).
*
* Ideally, use the call(Object, Method, Object...args) method when possible, as it will support any method, and
* also provides caching. There are times, however, when all that is passed in (REST APIs) is argument values,
* and if some of those are null, you may have an ambiguous targeted method. With this approach, you can still
* call these methods, assuming the methods are not overloaded with the same number of arguments and differing
* types.
*
* @param bean Object instance on which to call method.
* @param methodName String name of method to call.
* @param args Arguments to pass.
* @return Object value returned from the reflectively invoked method.
*/
public static Object call(Object bean, String methodName, Object... args)
{
Method method = getMethod(bean, methodName, args.length);
try
{
return method.invoke(bean, args);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("IllegalAccessException occurred attempting to reflectively call method: " + method.getName() + "()", e);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Exception thrown inside reflectively called method: " + method.getName() + "()", e.getTargetException());
}
}
/**
* Fetch the named method from the controller. First a local cache will be checked, and if not
* found, the method will be found reflectively on the controller. If the method is found, then
* it will be checked for a ControllerMethod annotation, which can indicate that it is NOT allowed
* to be called. This permits a public controller method to be blocked from remote access.
* @param bean Object on which the named method will be found.
* @param methodName String name of method to be located on the controller.
* @param argCount int number of arguments. This is used as part of the cache key to allow for
* duplicate method names as long as the argument list length is different.
*/
public static Method getMethod(Object bean, String methodName, int argCount)
{
if (bean == null)
{
throw new IllegalArgumentException("Attempted to call getMethod() [" + methodName + "()] on a null instance.");
}
if (methodName == null)
{
throw new IllegalArgumentException("Attempted to call getMethod() with a null method name on an instance of: " + bean.getClass().getName());
}
StringBuilder builder = new StringBuilder(bean.getClass().getName());
builder.append('.');
builder.append(methodName);
builder.append('|');
builder.append(argCount);
String methodKey = builder.toString();
Method method = METHOD_MAP2.get(methodKey);
if (method == null)
{
method = getMethod(bean.getClass(), methodName, argCount);
if (method == null)
{
throw new IllegalArgumentException("Method: " + methodName + "() is not found on class: " + bean.getClass().getName() + ". Perhaps the method is protected, private, or misspelled?");
}
Method other = METHOD_MAP2.putIfAbsent(methodKey, method);
if (other != null)
{
method = other;
}
}
return method;
}
/**
* Reflectively find the requested method on the requested class, only matching on argument count.
*/
private static Method getMethod(Class c, String methodName, int argc)
{
Method[] methods = c.getMethods();
for (Method method : methods)
{
if (methodName.equals(method.getName()) && method.getParameterTypes().length == argc)
{
return method;
}
}
return null;
}
/**
* Return the name of the class on the object, or "null" if the object is null.
* @param o Object to get the class name.
* @return String name of the class or "null"
*/
public static String getClassName(Object o)
{
return o == null ? "null" : o.getClass().getName();
}
/**
* Given a byte[] of a Java .class file (compiled Java), this code will retrieve the class name from those bytes.
* @param byteCode byte[] of compiled byte code.
* @return String name of class
* @throws Exception potential io exceptions can happen
*/
public static String getClassNameFromByteCode(byte[] byteCode) throws Exception
{
InputStream is = new ByteArrayInputStream(byteCode);
DataInputStream dis = new DataInputStream(is);
dis.readLong(); // skip header and class version
int cpcnt = (dis.readShort() & 0xffff) - 1;
int[] classes = new int[cpcnt];
String[] strings = new String[cpcnt];
for (int i=0; i < cpcnt; i++)
{
int t = dis.read();
if (t == 7)
{
classes[i] = dis.readShort() & 0xffff;
}
else if (t == 1)
{
strings[i] = dis.readUTF();
}
else if (t == 5 || t == 6)
{
dis.readLong();
i++;
}
else if (t == 8)
{
dis.readShort();
}
else
{
dis.readInt();
}
}
dis.readShort(); // skip access flags
return strings[classes[(dis.readShort() & 0xffff) - 1] - 1].replace('/', '.');
}
}
| src/main/java/com/cedarsoftware/util/ReflectionUtils.java | package com.cedarsoftware.util;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public final class ReflectionUtils
{
private static final ConcurrentMap<Class<?>, Collection<Field>> FIELD_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Method> METHOD_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Method> METHOD_MAP2 = new ConcurrentHashMap<>();
private ReflectionUtils()
{
super();
}
/**
* Determine if the passed in class (classToCheck) has the annotation (annoClass) on itself,
* any of its super classes, any of it's interfaces, or any of it's super interfaces.
* This is a exhaustive check throughout the complete inheritance hierarchy.
* @return the Annotation if found, null otherwise.
*/
public static <T extends Annotation> T getClassAnnotation(final Class<?> classToCheck, final Class<T> annoClass)
{
final Set<Class<?>> visited = new HashSet<>();
final LinkedList<Class<?>> stack = new LinkedList<>();
stack.add(classToCheck);
while (!stack.isEmpty())
{
Class<?> classToChk = stack.pop();
if (classToChk == null || visited.contains(classToChk))
{
continue;
}
visited.add(classToChk);
T a = (T) classToChk.getAnnotation(annoClass);
if (a != null)
{
return a;
}
stack.push(classToChk.getSuperclass());
addInterfaces(classToChk, stack);
}
return null;
}
private static void addInterfaces(final Class<?> classToCheck, final LinkedList<Class<?>> stack)
{
for (Class<?> interFace : classToCheck.getInterfaces())
{
stack.push(interFace);
}
}
public static <T extends Annotation> T getMethodAnnotation(final Method method, final Class<T> annoClass)
{
final Set<Class<?>> visited = new HashSet<>();
final LinkedList<Class<?>> stack = new LinkedList<>();
stack.add(method.getDeclaringClass());
while (!stack.isEmpty())
{
Class<?> classToChk = stack.pop();
if (classToChk == null || visited.contains(classToChk))
{
continue;
}
visited.add(classToChk);
Method m = getMethod(classToChk, method.getName(), method.getParameterTypes());
if (m == null)
{
continue;
}
T a = m.getAnnotation(annoClass);
if (a != null)
{
return a;
}
stack.push(classToChk.getSuperclass());
addInterfaces(method.getDeclaringClass(), stack);
}
return null;
}
/**
* Fetch a public method reflectively by name with argument types. This method caches the lookup, so that
* subsequent calls are significantly faster. The method can be on an inherited class of the passed in [starting]
* Class.
* @param c Class on which method is to be found.
* @param methodName String name of method to find.
* @param types Argument types for the method (null is used for no argument methods).
* @return Method located, or null if not found.
*/
public static Method getMethod(Class<?> c, String methodName, Class<?>...types)
{
try
{
StringBuilder builder = new StringBuilder(c.getName());
builder.append('.');
builder.append(methodName);
for (Class clz : types)
{
builder.append('|');
builder.append(clz.getName());
}
// methodKey is in form ClassName.methodName|arg1.class|arg2.class|...
String methodKey = builder.toString();
Method method = METHOD_MAP.get(methodKey);
if (method == null)
{
method = c.getMethod(methodName, types);
Method other = METHOD_MAP.putIfAbsent(methodKey, method);
if (other != null)
{
method = other;
}
}
return method;
}
catch (Exception nse)
{
return null;
}
}
/**
* Get all non static, non transient, fields of the passed in class, including
* private fields. Note, the special this$ field is also not returned. The result
* is cached in a static ConcurrentHashMap to benefit execution performance.
* @param c Class instance
* @return Collection of only the fields in the passed in class
* that would need further processing (reference fields). This
* makes field traversal on a class faster as it does not need to
* continually process known fields like primitives.
*/
public static Collection<Field> getDeepDeclaredFields(Class<?> c)
{
if (FIELD_MAP.containsKey(c))
{
return FIELD_MAP.get(c);
}
Collection<Field> fields = new ArrayList<>();
Class<?> curr = c;
while (curr != null)
{
getDeclaredFields(curr, fields);
curr = curr.getSuperclass();
}
FIELD_MAP.put(c, fields);
return fields;
}
/**
* Get all non static, non transient, fields of the passed in class, including
* private fields. Note, the special this$ field is also not returned. The
* resulting fields are stored in a Collection.
* @param c Class instance
* that would need further processing (reference fields). This
* makes field traversal on a class faster as it does not need to
* continually process known fields like primitives.
*/
public static void getDeclaredFields(Class<?> c, Collection<Field> fields) {
try
{
Field[] local = c.getDeclaredFields();
for (Field field : local)
{
try
{
field.setAccessible(true);
}
catch (Exception ignored) { }
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) &&
!field.getName().startsWith("this$") &&
!Modifier.isTransient(modifiers))
{ // speed up: do not count static fields, do not go back up to enclosing object in nested case, do not consider transients
fields.add(field);
}
}
}
catch (Throwable ignored)
{
ExceptionUtilities.safelyIgnoreException(ignored);
}
}
/**
* Return all Fields from a class (including inherited), mapped by
* String field name to java.lang.reflect.Field.
* @param c Class whose fields are being fetched.
* @return Map of all fields on the Class, keyed by String field
* name to java.lang.reflect.Field.
*/
public static Map<String, Field> getDeepDeclaredFieldMap(Class<?> c)
{
Map<String, Field> fieldMap = new HashMap<>();
Collection<Field> fields = getDeepDeclaredFields(c);
for (Field field : fields)
{
String fieldName = field.getName();
if (fieldMap.containsKey(fieldName))
{ // Can happen when parent and child class both have private field with same name
fieldMap.put(field.getDeclaringClass().getName() + '.' + fieldName, field);
}
else
{
fieldMap.put(fieldName, field);
}
}
return fieldMap;
}
/**
* Make reflective method calls without having to handle two checked exceptions (IllegalAccessException and
* InvocationTargetException). These exceptions are caught and rethrown as RuntimeExceptions, with the original
* exception passed (nested) on.
* @param bean Object (instance) on which to call method.
* @param method Method instance from target object [easily obtained by calling ReflectionUtils.getMethod()].
* @param args Arguments to pass to method.
* @return Object Value from reflectively called method.
*/
public static Object call(Object bean, Method method, Object... args)
{
if (method == null)
{
String className = bean == null ? "null bean" : bean.getClass().getName();
throw new IllegalArgumentException("null Method passed to ReflectionUtils.call() on bean of type: " + className);
}
if (bean == null)
{
throw new IllegalArgumentException("Cannot call [" + method.getName() + "()] on a null object.");
}
try
{
return method.invoke(bean, args);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("IllegalAccessException occurred attempting to reflectively call method: " + method.getName() + "()", e);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Exception thrown inside reflectively called method: " + method.getName() + "()", e.getTargetException());
}
}
/**
* Make a reflective method call in one step. This approach does not support calling two different methods with
* the same argument count, since it caches methods internally by "className.methodName|argCount". For example,
* if you had a class with two methods, foo(int, String) and foo(String, String), you cannot use this method.
* However, this method would support calling foo(int), foo(int, String), foo(int, String, Object), etc.
* Internally, it is caching the reflective method lookups as mentioned earlier for speed, using argument count
* as part of the key (not all argument types).
*
* Ideally, use the call(Object, Method, Object...args) method when possible, as it will support any method, and
* also provides caching. There are times, however, when all that is passed in (REST APIs) is argument types,
* and if some of thus are null, you may have an ambiguous targeted method. With this approach, you can still
* call these methods, assuming the methods are not overloaded with the same number of arguments and differing
* types.
*
* @param bean Object instance on which to call method.
* @param methodName String name of method to call.
* @param args Arguments to pass.
* @return Object value returned from the reflectively invoked method.
*/
public static Object call(Object bean, String methodName, Object... args)
{
Method method = getMethod(bean, methodName, args.length);
try
{
return method.invoke(bean, args);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("IllegalAccessException occurred attempting to reflectively call method: " + method.getName() + "()", e);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Exception thrown inside reflectively called method: " + method.getName() + "()", e.getTargetException());
}
}
/**
* Fetch the named method from the controller. First a local cache will be checked, and if not
* found, the method will be found reflectively on the controller. If the method is found, then
* it will be checked for a ControllerMethod annotation, which can indicate that it is NOT allowed
* to be called. This permits a public controller method to be blocked from remote access.
* @param bean Object on which the named method will be found.
* @param methodName String name of method to be located on the controller.
* @param argCount int number of arguments. This is used as part of the cache key to allow for
* duplicate method names as long as the argument list length is different.
*/
public static Method getMethod(Object bean, String methodName, int argCount)
{
if (bean == null)
{
throw new IllegalArgumentException("Attempted to call getMethod() [" + methodName + "()] on a null instance.");
}
if (methodName == null)
{
throw new IllegalArgumentException("Attempted to call getMethod() with a null method name on an instance of: " + bean.getClass().getName());
}
StringBuilder builder = new StringBuilder(bean.getClass().getName());
builder.append('.');
builder.append(methodName);
builder.append('|');
builder.append(argCount);
String methodKey = builder.toString();
Method method = METHOD_MAP2.get(methodKey);
if (method == null)
{
method = getMethod(bean.getClass(), methodName, argCount);
if (method == null)
{
throw new IllegalArgumentException("Method: " + methodName + "() is not found on class: " + bean.getClass().getName() + ". Perhaps the method is protected, private, or misspelled?");
}
Method other = METHOD_MAP2.putIfAbsent(methodKey, method);
if (other != null)
{
method = other;
}
}
return method;
}
/**
* Reflectively find the requested method on the requested class, only matching on argument count.
*/
private static Method getMethod(Class c, String methodName, int argc)
{
Method[] methods = c.getMethods();
for (Method method : methods)
{
if (methodName.equals(method.getName()) && method.getParameterTypes().length == argc)
{
return method;
}
}
return null;
}
/**
* Return the name of the class on the object, or "null" if the object is null.
* @param o Object to get the class name.
* @return String name of the class or "null"
*/
public static String getClassName(Object o)
{
return o == null ? "null" : o.getClass().getName();
}
/**
* Given a byte[] of a Java .class file (compiled Java), this code will retrieve the class name from those bytes.
* @param byteCode byte[] of compiled byte code.
* @return String name of class
* @throws Exception potential io exceptions can happen
*/
public static String getClassNameFromByteCode(byte[] byteCode) throws Exception
{
InputStream is = new ByteArrayInputStream(byteCode);
DataInputStream dis = new DataInputStream(is);
dis.readLong(); // skip header and class version
int cpcnt = (dis.readShort() & 0xffff) - 1;
int[] classes = new int[cpcnt];
String[] strings = new String[cpcnt];
for (int i=0; i < cpcnt; i++)
{
int t = dis.read();
if (t == 7)
{
classes[i] = dis.readShort() & 0xffff;
}
else if (t == 1)
{
strings[i] = dis.readUTF();
}
else if (t == 5 || t == 6)
{
dis.readLong();
i++;
}
else if (t == 8)
{
dis.readShort();
}
else
{
dis.readInt();
}
}
dis.readShort(); // skip access flags
return strings[classes[(dis.readShort() & 0xffff) - 1] - 1].replace('/', '.');
}
}
| comment changes
| src/main/java/com/cedarsoftware/util/ReflectionUtils.java | comment changes | <ide><path>rc/main/java/com/cedarsoftware/util/ReflectionUtils.java
<ide> import java.util.concurrent.ConcurrentMap;
<ide>
<ide> /**
<add> * Utilities to simplify writing reflective code as well as improve performance of reflective operations like
<add> * method and annotation lookups.
<add> *
<ide> * @author John DeRegnaucourt ([email protected])
<ide> * <br>
<ide> * Copyright (c) Cedar Software LLC
<ide> * as part of the key (not all argument types).
<ide> *
<ide> * Ideally, use the call(Object, Method, Object...args) method when possible, as it will support any method, and
<del> * also provides caching. There are times, however, when all that is passed in (REST APIs) is argument types,
<del> * and if some of thus are null, you may have an ambiguous targeted method. With this approach, you can still
<add> * also provides caching. There are times, however, when all that is passed in (REST APIs) is argument values,
<add> * and if some of those are null, you may have an ambiguous targeted method. With this approach, you can still
<ide> * call these methods, assuming the methods are not overloaded with the same number of arguments and differing
<ide> * types.
<ide> * |
|
Java | agpl-3.0 | 3018cc6719fb079af37663b04dec807e07ac0799 | 0 | kkronenb/kfs,quikkian-ua-devops/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs,kuali/kfs,bhutchinson/kfs,kuali/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kkronenb/kfs,ua-eas/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,smith750/kfs,kuali/kfs,smith750/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.module.labor.service.impl;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.kuali.PropertyConstants;
import org.kuali.core.service.DateTimeService;
import org.kuali.module.gl.bo.OriginEntryGroup;
import org.kuali.module.gl.bo.Transaction;
import org.kuali.module.gl.dao.OriginEntryDao;
import org.kuali.module.gl.service.OriginEntryGroupService;
import org.kuali.module.gl.service.impl.OriginEntryServiceImpl;
import org.kuali.module.gl.util.LedgerEntry;
import org.kuali.module.gl.util.LedgerEntryHolder;
import org.kuali.module.gl.util.OriginEntryStatistics;
import org.kuali.module.gl.util.PosterOutputSummaryEntry;
import org.kuali.module.labor.LaborConstants;
import org.kuali.module.labor.bo.LaborOriginEntry;
import org.kuali.module.labor.dao.LaborOriginEntryDao;
import org.kuali.module.labor.service.LaborOriginEntryService;
import org.kuali.module.labor.util.LaborLedgerUnitOfWork;
import org.kuali.module.labor.util.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
/**
* This class implements LaborOriginEntryService to provide the access to labor origin entries in data stores.
*/
@Transactional
public class LaborOriginEntryServiceImpl implements LaborOriginEntryService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OriginEntryServiceImpl.class);
private LaborOriginEntryDao laborOriginEntryDao;
private OriginEntryDao originEntryDao;
private OriginEntryGroupService originEntryGroupService;
private DateTimeService dateTimeService;
public OriginEntryStatistics getStatistics(Integer groupId) {
LOG.debug("getStatistics() started");
OriginEntryStatistics oes = new OriginEntryStatistics();
oes.setCreditTotalAmount(originEntryDao.getGroupTotal(groupId, true));
oes.setDebitTotalAmount(originEntryDao.getGroupTotal(groupId, false));
oes.setRowCount(originEntryDao.getGroupCount(groupId));
return oes;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#copyEntries(java.util.Date, java.lang.String, boolean, boolean, boolean,
* java.util.Collection)
*/
public OriginEntryGroup copyEntries(Date date, String sourceCode, boolean valid, boolean process, boolean scrub, Collection<LaborOriginEntry> entries) {
LOG.debug("copyEntries() started");
OriginEntryGroup newOriginEntryGroup = originEntryGroupService.createGroup(date, sourceCode, valid, process, scrub);
// Create new Entries with newOriginEntryGroup
for (LaborOriginEntry oe : entries) {
oe.setEntryGroupId(newOriginEntryGroup.getId());
createEntry(oe, newOriginEntryGroup);
}
return newOriginEntryGroup;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#delete(org.kuali.module.gl.bo.OriginEntry)
*/
public void delete(LaborOriginEntry loe) {
LOG.debug("deleteEntry() started");
originEntryDao.deleteEntry(loe);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getDocumentsByGroup(org.kuali.module.gl.bo.OriginEntryGroup)
*/
public Collection<LaborOriginEntry> getDocumentsByGroup(OriginEntryGroup oeg) {
LOG.debug("getDocumentsByGroup() started");
Collection<LaborOriginEntry> results = new ArrayList<LaborOriginEntry>();
Iterator i = originEntryDao.getDocumentsByGroup(oeg);
while (i.hasNext()) {
Object[] data = (Object[]) i.next();
LaborOriginEntry oe = new LaborOriginEntry();
oe.setDocumentNumber((String) data[0]);
oe.setFinancialDocumentTypeCode((String) data[1]);
oe.setFinancialSystemOriginationCode((String) data[2]);
results.add(oe);
}
return results;
}
public Iterator<LaborOriginEntry> getBadBalanceEntries(Collection groups) {
LOG.debug("getBadBalanceEntries() started");
Iterator returnVal = originEntryDao.getBadBalanceEntries(groups);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupAccountOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, OriginEntryDao.SORT_ACCOUNT);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupReportOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, originEntryDao.SORT_REPORT);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupListingReportOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, originEntryDao.SORT_LISTING_REPORT);
return returnVal;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getEntriesByDocument(org.kuali.module.gl.bo.OriginEntryGroup,
* java.lang.String, java.lang.String, java.lang.String)
*/
public Iterator<LaborOriginEntry> getEntriesByDocument(OriginEntryGroup originEntryGroup, String documentNumber, String documentTypeCode, String originCode) {
LOG.debug("getEntriesByGroup() started");
Map criteria = new HashMap();
criteria.put(PropertyConstants.ENTRY_GROUP_ID, originEntryGroup.getId());
criteria.put(PropertyConstants.DOCUMENT_NUMBER, documentNumber);
criteria.put(PropertyConstants.FINANCIAL_DOCUMENT_TYPE_CODE, documentTypeCode);
criteria.put(PropertyConstants.FINANCIAL_SYSTEM_ORIGINATION_CODE, originCode);
return originEntryDao.getMatchingEntries(criteria);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#createEntry(org.kuali.module.gl.bo.Transaction,
* org.kuali.module.gl.bo.OriginEntryGroup)
*/
public void createEntry(Transaction transaction, OriginEntryGroup originEntryGroup) {
LOG.debug("createEntry() started");
LaborOriginEntry e = new LaborOriginEntry(transaction);
e.setGroup(originEntryGroup);
originEntryDao.saveOriginEntry(e);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#save(org.kuali.module.gl.bo.OriginEntry)
*/
public void save(LaborOriginEntry entry) {
LOG.debug("save() started");
originEntryDao.saveOriginEntry(entry);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#exportFlatFile(java.lang.String, java.lang.Integer)
*/
public void exportFlatFile(String filename, Integer groupId) {
LOG.debug("exportFlatFile() started");
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(filename));
OriginEntryGroup oeg = new OriginEntryGroup();
oeg.setId(groupId);
Iterator i = getEntriesByGroup(oeg);
while (i.hasNext()) {
LaborOriginEntry e = (LaborOriginEntry) i.next();
out.write(e.getLine() + "\n");
}
}
catch (IOException e) {
LOG.error("exportFlatFile() Error writing to file", e);
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException ie) {
LOG.error("exportFlatFile() Error closing file", ie);
}
}
}
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#loadFlatFile(java.lang.String, java.lang.String, boolean, boolean,
* boolean)
*/
public void loadFlatFile(String filename, String groupSourceCode, boolean isValid, boolean isProcessed, boolean isScrub) {
LOG.debug("loadFlatFile() started");
java.sql.Date groupDate = new java.sql.Date(dateTimeService.getCurrentDate().getTime());
OriginEntryGroup newGroup = originEntryGroupService.createGroup(groupDate, groupSourceCode, isValid, isProcessed, isScrub);
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = input.readLine()) != null) {
LaborOriginEntry entry = new LaborOriginEntry(line);
createEntry(entry, newGroup);
}
}
catch (Exception ex) {
LOG.error("performStep() Error reading file", ex);
throw new IllegalArgumentException("Error reading file");
}
finally {
try {
if (input != null) {
input.close();
}
}
catch (IOException ex) {
LOG.error("loadFlatFile() error closing file.", ex);
}
}
}
public LedgerEntryHolder getSummaryByGroupId(Collection groupIdList) {
LOG.debug("getSummaryByGroupId() started");
LedgerEntryHolder ledgerEntryHolder = new LedgerEntryHolder();
if (groupIdList.size() == 0) {
return ledgerEntryHolder;
}
Iterator entrySummaryIterator = originEntryDao.getSummaryByGroupId(groupIdList);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
LedgerEntry ledgerEntry = LedgerEntry.buildLedgerEntry(entrySummary);
ledgerEntryHolder.insertLedgerEntry(ledgerEntry, true);
}
return ledgerEntryHolder;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#flatFile(java.lang.Integer, java.io.BufferedOutputStream)
*/
public void flatFile(Integer groupId, BufferedOutputStream bw) {
LOG.debug("flatFile() started");
try {
OriginEntryGroup oeg = new OriginEntryGroup();
oeg.setId(groupId);
Iterator i = getEntriesByGroup(oeg);
while (i.hasNext()) {
LaborOriginEntry e = (LaborOriginEntry) i.next();
bw.write((e.getLine() + "\n").getBytes());
}
}
catch (IOException e) {
LOG.error("flatFile() Error writing to file", e);
throw new RuntimeException("Error writing to file: " + e.getMessage());
}
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getMatchingEntriesByCollection(java.util.Map)
*/
public Collection getMatchingEntriesByCollection(Map searchCriteria) {
LOG.debug("getMatchingEntriesByCollection() started");
return originEntryDao.getMatchingEntriesByCollection(searchCriteria);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getExactMatchingEntry(java.lang.Integer)
*/
public LaborOriginEntry getExactMatchingEntry(Integer entryId) {
LOG.debug("getExactMatchingEntry() started");
return (LaborOriginEntry) originEntryDao.getExactMatchingEntry(entryId);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroup(org.kuali.module.gl.bo.OriginEntryGroup)
*/
public Iterator<LaborOriginEntry> getEntriesByGroup(OriginEntryGroup group) {
return laborOriginEntryDao.getEntriesByGroup(group);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroups(java.util.Collection)
*/
public Iterator<LaborOriginEntry> getEntriesByGroups(Collection<OriginEntryGroup> groups) {
return laborOriginEntryDao.getEntriesByGroups(groups);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroup(org.kuali.module.gl.bo.OriginEntryGroup,
* boolean)
*/
public Iterator<LaborOriginEntry> getEntriesByGroup(OriginEntryGroup group, boolean isConsolidated) {
if (!isConsolidated) {
return this.getEntriesByGroup(group);
}
Collection<LaborOriginEntry> entryCollection = new ArrayList<LaborOriginEntry>();
LaborLedgerUnitOfWork laborLedgerUnitOfWork = new LaborLedgerUnitOfWork();
Iterator<Object[]> consolidatedEntries = laborOriginEntryDao.getConsolidatedEntriesByGroup(group);
while (consolidatedEntries.hasNext()) {
LaborOriginEntry laborOriginEntry = new LaborOriginEntry();
Object[] oneEntry = consolidatedEntries.next();
ObjectUtil.buildObject(laborOriginEntry, oneEntry, LaborConstants.consolidationAttributesOfOriginEntry());
if (laborLedgerUnitOfWork.canContain(laborOriginEntry)) {
laborLedgerUnitOfWork.addEntryIntoUnit(laborOriginEntry);
}
else {
entryCollection.add(laborLedgerUnitOfWork.getWorkingEntry());
laborLedgerUnitOfWork.resetLaborLedgerUnitOfWork(laborOriginEntry);
}
}
return entryCollection.iterator();
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getSummariedEntriesByGroups(java.util.Collection)
*/
public LedgerEntryHolder getSummariedEntriesByGroups(Collection<OriginEntryGroup> groups) {
LedgerEntryHolder ledgerEntryHolder = new LedgerEntryHolder();
if (groups.size() > 0) {
Iterator entrySummaryIterator = laborOriginEntryDao.getSummaryByGroupId(groups);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
ledgerEntryHolder.insertLedgerEntry(LedgerEntry.buildLedgerEntry(entrySummary), true);
}
}
return ledgerEntryHolder;
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getPosterOutputSummaryByGroups(java.util.Collection)
*/
public Map<String, PosterOutputSummaryEntry> getPosterOutputSummaryByGroups(Collection<OriginEntryGroup> groups) {
Map<String, PosterOutputSummaryEntry> outputSummary = new HashMap<String, PosterOutputSummaryEntry>();
Iterator entrySummaryIterator = laborOriginEntryDao.getPosterOutputSummaryByGroupId(groups);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
PosterOutputSummaryEntry posterOutputSummaryEntry = PosterOutputSummaryEntry.buildPosterOutputSummaryEntry(entrySummary);
if (outputSummary.containsKey(posterOutputSummaryEntry.getKey())) {
PosterOutputSummaryEntry tempEntry = outputSummary.get(posterOutputSummaryEntry.getKey());
tempEntry.add(posterOutputSummaryEntry);
}
else {
outputSummary.put(posterOutputSummaryEntry.getKey(), posterOutputSummaryEntry);
}
}
return outputSummary;
}
/**
* Sets the dateTimeService attribute value.
*
* @param dateTimeService The dateTimeService to set.
*/
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
/**
* Sets the laborOriginEntryDao attribute value.
*
* @param laborOriginEntryDao The laborOriginEntryDao to set.
*/
public void setLaborOriginEntryDao(LaborOriginEntryDao laborOriginEntryDao) {
this.laborOriginEntryDao = laborOriginEntryDao;
}
/**
* Sets the originEntryDao attribute value.
*
* @param originEntryDao The originEntryDao to set.
*/
public void setOriginEntryDao(OriginEntryDao originEntryDao) {
this.originEntryDao = originEntryDao;
}
/**
* Sets the originEntryGroupService attribute value.
*
* @param originEntryGroupService The originEntryGroupService to set.
*/
public void setOriginEntryGroupService(OriginEntryGroupService originEntryGroupService) {
this.originEntryGroupService = originEntryGroupService;
}
} | work/src/org/kuali/kfs/module/ld/service/impl/LaborOriginEntryServiceImpl.java | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.module.labor.service.impl;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.kuali.PropertyConstants;
import org.kuali.core.service.DateTimeService;
import org.kuali.module.gl.bo.OriginEntryGroup;
import org.kuali.module.gl.bo.Transaction;
import org.kuali.module.gl.dao.OriginEntryDao;
import org.kuali.module.gl.service.OriginEntryGroupService;
import org.kuali.module.gl.service.impl.OriginEntryServiceImpl;
import org.kuali.module.gl.util.LedgerEntry;
import org.kuali.module.gl.util.LedgerEntryHolder;
import org.kuali.module.gl.util.OriginEntryStatistics;
import org.kuali.module.gl.util.PosterOutputSummaryEntry;
import org.kuali.module.labor.LaborConstants;
import org.kuali.module.labor.bo.LaborOriginEntry;
import org.kuali.module.labor.dao.LaborOriginEntryDao;
import org.kuali.module.labor.service.LaborOriginEntryService;
import org.kuali.module.labor.util.LaborLedgerUnitOfWork;
import org.kuali.module.labor.util.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
/**
* This class implements LaborOriginEntryService to provide the access to labor origin entries in data stores.
*/
@Transactional
public class LaborOriginEntryServiceImpl implements LaborOriginEntryService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OriginEntryServiceImpl.class);
private static final String ENTRY_GROUP_ID = "entryGroupId";
private static final String FINANCIAL_DOCUMENT_TYPE_CODE = "financialDocumentTypeCode";
private static final String FINANCIAL_SYSTEM_ORIGINATION_CODE = "financialSystemOriginationCode";
private LaborOriginEntryDao laborOriginEntryDao;
private OriginEntryDao originEntryDao;
private OriginEntryGroupService originEntryGroupService;
private DateTimeService dateTimeService;
public OriginEntryStatistics getStatistics(Integer groupId) {
LOG.debug("getStatistics() started");
OriginEntryStatistics oes = new OriginEntryStatistics();
oes.setCreditTotalAmount(originEntryDao.getGroupTotal(groupId, true));
oes.setDebitTotalAmount(originEntryDao.getGroupTotal(groupId, false));
oes.setRowCount(originEntryDao.getGroupCount(groupId));
return oes;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#copyEntries(java.util.Date, java.lang.String, boolean, boolean, boolean,
* java.util.Collection)
*/
public OriginEntryGroup copyEntries(Date date, String sourceCode, boolean valid, boolean process, boolean scrub, Collection<LaborOriginEntry> entries) {
LOG.debug("copyEntries() started");
OriginEntryGroup newOriginEntryGroup = originEntryGroupService.createGroup(date, sourceCode, valid, process, scrub);
// Create new Entries with newOriginEntryGroup
for (LaborOriginEntry oe : entries) {
oe.setEntryGroupId(newOriginEntryGroup.getId());
createEntry(oe, newOriginEntryGroup);
}
return newOriginEntryGroup;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#delete(org.kuali.module.gl.bo.OriginEntry)
*/
public void delete(LaborOriginEntry loe) {
LOG.debug("deleteEntry() started");
originEntryDao.deleteEntry(loe);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getDocumentsByGroup(org.kuali.module.gl.bo.OriginEntryGroup)
*/
public Collection<LaborOriginEntry> getDocumentsByGroup(OriginEntryGroup oeg) {
LOG.debug("getDocumentsByGroup() started");
Collection<LaborOriginEntry> results = new ArrayList<LaborOriginEntry>();
Iterator i = originEntryDao.getDocumentsByGroup(oeg);
while (i.hasNext()) {
Object[] data = (Object[]) i.next();
LaborOriginEntry oe = new LaborOriginEntry();
oe.setDocumentNumber((String) data[0]);
oe.setFinancialDocumentTypeCode((String) data[1]);
oe.setFinancialSystemOriginationCode((String) data[2]);
results.add(oe);
}
return results;
}
public Iterator<LaborOriginEntry> getBadBalanceEntries(Collection groups) {
LOG.debug("getBadBalanceEntries() started");
Iterator returnVal = originEntryDao.getBadBalanceEntries(groups);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupAccountOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, OriginEntryDao.SORT_ACCOUNT);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupReportOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, originEntryDao.SORT_REPORT);
return returnVal;
}
public Iterator<LaborOriginEntry> getEntriesByGroupListingReportOrder(OriginEntryGroup oeg) {
LOG.debug("getEntriesByGroupAccountOrder() started");
Iterator returnVal = originEntryDao.getEntriesByGroup(oeg, originEntryDao.SORT_LISTING_REPORT);
return returnVal;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getEntriesByDocument(org.kuali.module.gl.bo.OriginEntryGroup,
* java.lang.String, java.lang.String, java.lang.String)
*/
public Iterator<LaborOriginEntry> getEntriesByDocument(OriginEntryGroup originEntryGroup, String documentNumber, String documentTypeCode, String originCode) {
LOG.debug("getEntriesByGroup() started");
Map criteria = new HashMap();
criteria.put(ENTRY_GROUP_ID, originEntryGroup.getId());
criteria.put(PropertyConstants.DOCUMENT_NUMBER, documentNumber);
criteria.put(FINANCIAL_DOCUMENT_TYPE_CODE, documentTypeCode);
criteria.put(FINANCIAL_SYSTEM_ORIGINATION_CODE, originCode);
return originEntryDao.getMatchingEntries(criteria);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#createEntry(org.kuali.module.gl.bo.Transaction,
* org.kuali.module.gl.bo.OriginEntryGroup)
*/
public void createEntry(Transaction transaction, OriginEntryGroup originEntryGroup) {
LOG.debug("createEntry() started");
LaborOriginEntry e = new LaborOriginEntry(transaction);
e.setGroup(originEntryGroup);
originEntryDao.saveOriginEntry(e);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#save(org.kuali.module.gl.bo.OriginEntry)
*/
public void save(LaborOriginEntry entry) {
LOG.debug("save() started");
originEntryDao.saveOriginEntry(entry);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#exportFlatFile(java.lang.String, java.lang.Integer)
*/
public void exportFlatFile(String filename, Integer groupId) {
LOG.debug("exportFlatFile() started");
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(filename));
OriginEntryGroup oeg = new OriginEntryGroup();
oeg.setId(groupId);
Iterator i = getEntriesByGroup(oeg);
while (i.hasNext()) {
LaborOriginEntry e = (LaborOriginEntry) i.next();
out.write(e.getLine() + "\n");
}
}
catch (IOException e) {
LOG.error("exportFlatFile() Error writing to file", e);
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException ie) {
LOG.error("exportFlatFile() Error closing file", ie);
}
}
}
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#loadFlatFile(java.lang.String, java.lang.String, boolean, boolean,
* boolean)
*/
public void loadFlatFile(String filename, String groupSourceCode, boolean isValid, boolean isProcessed, boolean isScrub) {
LOG.debug("loadFlatFile() started");
java.sql.Date groupDate = new java.sql.Date(dateTimeService.getCurrentDate().getTime());
OriginEntryGroup newGroup = originEntryGroupService.createGroup(groupDate, groupSourceCode, isValid, isProcessed, isScrub);
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = input.readLine()) != null) {
LaborOriginEntry entry = new LaborOriginEntry(line);
createEntry(entry, newGroup);
}
}
catch (Exception ex) {
LOG.error("performStep() Error reading file", ex);
throw new IllegalArgumentException("Error reading file");
}
finally {
try {
if (input != null) {
input.close();
}
}
catch (IOException ex) {
LOG.error("loadFlatFile() error closing file.", ex);
}
}
}
public LedgerEntryHolder getSummaryByGroupId(Collection groupIdList) {
LOG.debug("getSummaryByGroupId() started");
LedgerEntryHolder ledgerEntryHolder = new LedgerEntryHolder();
if (groupIdList.size() == 0) {
return ledgerEntryHolder;
}
Iterator entrySummaryIterator = originEntryDao.getSummaryByGroupId(groupIdList);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
LedgerEntry ledgerEntry = LedgerEntry.buildLedgerEntry(entrySummary);
ledgerEntryHolder.insertLedgerEntry(ledgerEntry, true);
}
return ledgerEntryHolder;
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#flatFile(java.lang.Integer, java.io.BufferedOutputStream)
*/
public void flatFile(Integer groupId, BufferedOutputStream bw) {
LOG.debug("flatFile() started");
try {
OriginEntryGroup oeg = new OriginEntryGroup();
oeg.setId(groupId);
Iterator i = getEntriesByGroup(oeg);
while (i.hasNext()) {
LaborOriginEntry e = (LaborOriginEntry) i.next();
bw.write((e.getLine() + "\n").getBytes());
}
}
catch (IOException e) {
LOG.error("flatFile() Error writing to file", e);
throw new RuntimeException("Error writing to file: " + e.getMessage());
}
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getMatchingEntriesByCollection(java.util.Map)
*/
public Collection getMatchingEntriesByCollection(Map searchCriteria) {
LOG.debug("getMatchingEntriesByCollection() started");
return originEntryDao.getMatchingEntriesByCollection(searchCriteria);
}
/**
* @see org.kuali.module.gl.service.OriginEntryService#getExactMatchingEntry(java.lang.Integer)
*/
public LaborOriginEntry getExactMatchingEntry(Integer entryId) {
LOG.debug("getExactMatchingEntry() started");
return (LaborOriginEntry) originEntryDao.getExactMatchingEntry(entryId);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroup(org.kuali.module.gl.bo.OriginEntryGroup)
*/
public Iterator<LaborOriginEntry> getEntriesByGroup(OriginEntryGroup group) {
return laborOriginEntryDao.getEntriesByGroup(group);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroups(java.util.Collection)
*/
public Iterator<LaborOriginEntry> getEntriesByGroups(Collection<OriginEntryGroup> groups) {
return laborOriginEntryDao.getEntriesByGroups(groups);
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getEntriesByGroup(org.kuali.module.gl.bo.OriginEntryGroup,
* boolean)
*/
public Iterator<LaborOriginEntry> getEntriesByGroup(OriginEntryGroup group, boolean isConsolidated) {
if (!isConsolidated) {
return this.getEntriesByGroup(group);
}
Collection<LaborOriginEntry> entryCollection = new ArrayList<LaborOriginEntry>();
LaborLedgerUnitOfWork laborLedgerUnitOfWork = new LaborLedgerUnitOfWork();
Iterator<Object[]> consolidatedEntries = laborOriginEntryDao.getConsolidatedEntriesByGroup(group);
while (consolidatedEntries.hasNext()) {
LaborOriginEntry laborOriginEntry = new LaborOriginEntry();
Object[] oneEntry = consolidatedEntries.next();
ObjectUtil.buildObject(laborOriginEntry, oneEntry, LaborConstants.consolidationAttributesOfOriginEntry());
if (laborLedgerUnitOfWork.canContain(laborOriginEntry)) {
laborLedgerUnitOfWork.addEntryIntoUnit(laborOriginEntry);
}
else {
entryCollection.add(laborLedgerUnitOfWork.getWorkingEntry());
laborLedgerUnitOfWork.resetLaborLedgerUnitOfWork(laborOriginEntry);
}
}
return entryCollection.iterator();
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getSummariedEntriesByGroups(java.util.Collection)
*/
public LedgerEntryHolder getSummariedEntriesByGroups(Collection<OriginEntryGroup> groups) {
LedgerEntryHolder ledgerEntryHolder = new LedgerEntryHolder();
if (groups.size() > 0) {
Iterator entrySummaryIterator = laborOriginEntryDao.getSummaryByGroupId(groups);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
ledgerEntryHolder.insertLedgerEntry(LedgerEntry.buildLedgerEntry(entrySummary), true);
}
}
return ledgerEntryHolder;
}
/**
* @see org.kuali.module.labor.service.LaborOriginEntryService#getPosterOutputSummaryByGroups(java.util.Collection)
*/
public Map<String, PosterOutputSummaryEntry> getPosterOutputSummaryByGroups(Collection<OriginEntryGroup> groups) {
Map<String, PosterOutputSummaryEntry> outputSummary = new HashMap<String, PosterOutputSummaryEntry>();
Iterator entrySummaryIterator = laborOriginEntryDao.getPosterOutputSummaryByGroupId(groups);
while (entrySummaryIterator.hasNext()) {
Object[] entrySummary = (Object[]) entrySummaryIterator.next();
PosterOutputSummaryEntry posterOutputSummaryEntry = PosterOutputSummaryEntry.buildPosterOutputSummaryEntry(entrySummary);
if (outputSummary.containsKey(posterOutputSummaryEntry.getKey())) {
PosterOutputSummaryEntry tempEntry = outputSummary.get(posterOutputSummaryEntry.getKey());
tempEntry.add(posterOutputSummaryEntry);
}
else {
outputSummary.put(posterOutputSummaryEntry.getKey(), posterOutputSummaryEntry);
}
}
return outputSummary;
}
/**
* Sets the dateTimeService attribute value.
*
* @param dateTimeService The dateTimeService to set.
*/
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
/**
* Sets the laborOriginEntryDao attribute value.
*
* @param laborOriginEntryDao The laborOriginEntryDao to set.
*/
public void setLaborOriginEntryDao(LaborOriginEntryDao laborOriginEntryDao) {
this.laborOriginEntryDao = laborOriginEntryDao;
}
/**
* Sets the originEntryDao attribute value.
*
* @param originEntryDao The originEntryDao to set.
*/
public void setOriginEntryDao(OriginEntryDao originEntryDao) {
this.originEntryDao = originEntryDao;
}
/**
* Sets the originEntryGroupService attribute value.
*
* @param originEntryGroupService The originEntryGroupService to set.
*/
public void setOriginEntryGroupService(OriginEntryGroupService originEntryGroupService) {
this.originEntryGroupService = originEntryGroupService;
}
} | Replace the following constants with those in PropertyConstants
ENTRY_GROUP_ID;
FINANCIAL_DOCUMENT_TYPE_CODE;
FINANCIAL_SYSTEM_ORIGINATION_CODE
| work/src/org/kuali/kfs/module/ld/service/impl/LaborOriginEntryServiceImpl.java | Replace the following constants with those in PropertyConstants ENTRY_GROUP_ID; FINANCIAL_DOCUMENT_TYPE_CODE; FINANCIAL_SYSTEM_ORIGINATION_CODE | <ide><path>ork/src/org/kuali/kfs/module/ld/service/impl/LaborOriginEntryServiceImpl.java
<ide> public class LaborOriginEntryServiceImpl implements LaborOriginEntryService {
<ide> private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OriginEntryServiceImpl.class);
<ide>
<del> private static final String ENTRY_GROUP_ID = "entryGroupId";
<del> private static final String FINANCIAL_DOCUMENT_TYPE_CODE = "financialDocumentTypeCode";
<del> private static final String FINANCIAL_SYSTEM_ORIGINATION_CODE = "financialSystemOriginationCode";
<del>
<ide> private LaborOriginEntryDao laborOriginEntryDao;
<ide> private OriginEntryDao originEntryDao;
<ide> private OriginEntryGroupService originEntryGroupService;
<ide> LOG.debug("getEntriesByGroup() started");
<ide>
<ide> Map criteria = new HashMap();
<del> criteria.put(ENTRY_GROUP_ID, originEntryGroup.getId());
<add> criteria.put(PropertyConstants.ENTRY_GROUP_ID, originEntryGroup.getId());
<ide> criteria.put(PropertyConstants.DOCUMENT_NUMBER, documentNumber);
<del> criteria.put(FINANCIAL_DOCUMENT_TYPE_CODE, documentTypeCode);
<del> criteria.put(FINANCIAL_SYSTEM_ORIGINATION_CODE, originCode);
<add> criteria.put(PropertyConstants.FINANCIAL_DOCUMENT_TYPE_CODE, documentTypeCode);
<add> criteria.put(PropertyConstants.FINANCIAL_SYSTEM_ORIGINATION_CODE, originCode);
<ide>
<ide> return originEntryDao.getMatchingEntries(criteria);
<ide> } |
|
Java | apache-2.0 | b9fa8b1e6fa805d316d669a61901788cdfdd5831 | 0 | Distrotech/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,caot/intellij-community,youdonghai/intellij-community,allotria/intellij-community,semonte/intellij-community,supersven/intellij-community,ahb0327/intellij-community,slisson/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,asedunov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,supersven/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,signed/intellij-community,ibinti/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,jagguli/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,hurricup/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,allotria/intellij-community,da1z/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,diorcety/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,allotria/intellij-community,clumsy/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,fitermay/intellij-community,jagguli/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,caot/intellij-community,holmes/intellij-community,kdwink/intellij-community,izonder/intellij-community,izonder/intellij-community,fitermay/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,allotria/intellij-community,diorcety/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,fnouama/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,kool79/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,semonte/intellij-community,vladmm/intellij-community,kool79/intellij-community,asedunov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,gnuhub/intellij-community,izonder/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,adedayo/intellij-community,izonder/intellij-community,xfournet/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,da1z/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,fitermay/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,semonte/intellij-community,vvv1559/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ryano144/intellij-community,apixandru/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,izonder/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fitermay/intellij-community,holmes/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,amith01994/intellij-community,petteyg/intellij-community,vladmm/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,xfournet/intellij-community,FHannes/intellij-community,jagguli/intellij-community,retomerz/intellij-community,xfournet/intellij-community,samthor/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,blademainer/intellij-community,da1z/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,semonte/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,robovm/robovm-studio,kdwink/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,samthor/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,allotria/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,izonder/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,FHannes/intellij-community,fnouama/intellij-community,slisson/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,signed/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,clumsy/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kdwink/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,signed/intellij-community,samthor/intellij-community,retomerz/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,blademainer/intellij-community,da1z/intellij-community,hurricup/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,signed/intellij-community,fnouama/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,samthor/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,kool79/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fitermay/intellij-community,amith01994/intellij-community,robovm/robovm-studio,vladmm/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,supersven/intellij-community,Lekanich/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,signed/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,retomerz/intellij-community,supersven/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,kool79/intellij-community,samthor/intellij-community,adedayo/intellij-community,FHannes/intellij-community,holmes/intellij-community,signed/intellij-community,holmes/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,samthor/intellij-community,jagguli/intellij-community,caot/intellij-community,TangHao1987/intellij-community,caot/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ryano144/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,signed/intellij-community,jagguli/intellij-community,kool79/intellij-community,FHannes/intellij-community,diorcety/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,holmes/intellij-community,fitermay/intellij-community,fitermay/intellij-community,izonder/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,caot/intellij-community,asedunov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,da1z/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,retomerz/intellij-community,signed/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,apixandru/intellij-community,kool79/intellij-community,apixandru/intellij-community,slisson/intellij-community,xfournet/intellij-community,supersven/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ftomassetti/intellij-community,caot/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,semonte/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,fnouama/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,asedunov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,signed/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ibinti/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,izonder/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,SerCeMan/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,adedayo/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,kdwink/intellij-community,caot/intellij-community,samthor/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,holmes/intellij-community,asedunov/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,apixandru/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,slisson/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.plugins;
import com.intellij.CommonBundle;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.ide.startup.StartupActionScriptManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.options.ex.SingleConfigurableEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.Function;
import com.intellij.util.ui.StatusText;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
/**
* User: anna
*/
public class InstalledPluginsManagerMain extends PluginManagerMain {
public InstalledPluginsManagerMain(PluginManagerUISettings uiSettings) {
super(uiSettings);
init();
myActionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
final JButton jbButton = new JButton("Install JetBrains plugin...");
jbButton.setMnemonic('j');
jbButton.addActionListener(new BrowseRepoListener("JetBrains"));
myActionsPanel.add(jbButton);
final JButton button = new JButton("Browse repositories...");
button.setMnemonic('b');
button.addActionListener(new BrowseRepoListener(null));
myActionsPanel.add(button);
final JButton installPluginFromFileSystem = new JButton("Install plugin from disk...");
installPluginFromFileSystem.setMnemonic('d');
installPluginFromFileSystem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, false){
@Override
public boolean isFileSelectable(VirtualFile file) {
final String extension = file.getExtension();
return Comparing.strEqual(extension, "jar") || Comparing.strEqual(extension, "zip");
}
};
descriptor.setTitle("Choose Plugin File");
descriptor.setDescription("JAR and ZIP archives are accepted");
FileChooser.chooseFiles(descriptor, null, myActionsPanel, null, new FileChooser.FileChooserConsumer() {
@Override
public void cancelled() {
}
@Override
public void consume(List<VirtualFile> files) {
if (files != null && files.size() == 1) {
VirtualFile virtualFile = files.get(0);
if (virtualFile != null) {
final File file = VfsUtilCore.virtualToIoFile(virtualFile);
try {
final IdeaPluginDescriptorImpl pluginDescriptor = PluginDownloader.loadDescriptionFromJar(file);
if (pluginDescriptor == null) {
Messages.showErrorDialog("Fail to load plugin descriptor from file " + file.getName(), CommonBundle.getErrorTitle());
return;
}
if (PluginManagerCore.isIncompatible(pluginDescriptor)) {
Messages.showErrorDialog("Plugin " + pluginDescriptor.getName() + " is incompatible with current installation", CommonBundle.getErrorTitle());
return;
}
final IdeaPluginDescriptor alreadyInstalledPlugin = PluginManager.getPlugin(pluginDescriptor.getPluginId());
if (alreadyInstalledPlugin != null) {
final File oldFile = alreadyInstalledPlugin.getPath();
if (oldFile != null) {
StartupActionScriptManager.addActionCommand(new StartupActionScriptManager.DeleteCommand(oldFile));
}
}
if (((InstalledPluginsTableModel)pluginsModel).appendOrUpdateDescriptor(pluginDescriptor)) {
PluginDownloader.install(file, file.getName(), false);
select(pluginDescriptor);
checkInstalledPluginDependencies(pluginDescriptor);
setRequireShutdown(true);
}
else {
Messages.showInfoMessage(myActionsPanel, "Plugin " + pluginDescriptor.getName() + " was already installed",
CommonBundle.getWarningTitle());
}
}
catch (IOException ex) {
Messages.showErrorDialog(ex.getMessage(), CommonBundle.getErrorTitle());
}
}
}
}
});
}
});
myActionsPanel.add(installPluginFromFileSystem);
final StatusText emptyText = pluginTable.getEmptyText();
emptyText.setText("Nothing to show.");
emptyText.appendText(" Click ");
emptyText.appendText("Browse", SimpleTextAttributes.LINK_ATTRIBUTES, new BrowseRepoListener(null));
emptyText.appendText(" to search for non-bundled plugins.");
}
private void checkInstalledPluginDependencies(IdeaPluginDescriptorImpl pluginDescriptor) {
final Set<PluginId> notInstalled = new HashSet<PluginId>();
final Set<PluginId> disabledIds = new HashSet<PluginId>();
final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds();
for (PluginId id : dependentPluginIds) {
if (ArrayUtilRt.find(optionalDependentPluginIds, id) > -1) continue;
final boolean disabled = ((InstalledPluginsTableModel)pluginsModel).isDisabled(id);
final boolean enabled = ((InstalledPluginsTableModel)pluginsModel).isEnabled(id);
if (!enabled && !disabled && !PluginManagerCore.isModuleDependency(id)) {
notInstalled.add(id);
} else if (disabled) {
disabledIds.add(id);
}
}
if (!notInstalled.isEmpty()) {
Messages.showWarningDialog("Plugin " +
pluginDescriptor.getName() +
" depends on unknown plugin" +
(notInstalled.size() > 1 ? "s " : " ") +
StringUtil.join(notInstalled, new Function<PluginId, String>() {
@Override
public String fun(PluginId id) {
return id.toString();
}
}, ", "), CommonBundle.getWarningTitle());
}
if (!disabledIds.isEmpty()) {
final Set<IdeaPluginDescriptor> dependencies = new HashSet<IdeaPluginDescriptor>();
for (IdeaPluginDescriptor ideaPluginDescriptor : pluginsModel.view) {
if (disabledIds.contains(ideaPluginDescriptor.getPluginId())) {
dependencies.add(ideaPluginDescriptor);
}
}
final String disabledPluginsMessage = "disabled plugin" + (dependencies.size() > 1 ? "s " : " ");
String message = "Plugin " +
pluginDescriptor.getName() +
" depends on " +
disabledPluginsMessage +
StringUtil.join(dependencies, new Function<IdeaPluginDescriptor, String>() {
@Override
public String fun(IdeaPluginDescriptor ideaPluginDescriptor) {
return ideaPluginDescriptor.getName();
}
}, ", ") +
". Enable " + disabledPluginsMessage.trim() + "?";
if (Messages.showOkCancelDialog(myActionsPanel, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) ==
DialogWrapper.OK_EXIT_CODE) {
((InstalledPluginsTableModel)pluginsModel).enableRows(dependencies.toArray(new IdeaPluginDescriptor[dependencies.size()]), Boolean.TRUE);
}
}
}
@Override
protected void propagateUpdates(List<IdeaPluginDescriptor> list) {
}
private PluginManagerConfigurable createAvailableConfigurable(final String vendorFilter) {
return new PluginManagerConfigurable(PluginManagerUISettings.getInstance(), true) {
@Override
protected PluginManagerMain createPanel() {
return new AvailablePluginsManagerMain(InstalledPluginsManagerMain.this, myUISettings, vendorFilter);
}
@Override
public String getDisplayName() {
return vendorFilter != null ? "Browse " + vendorFilter + " Plugins " : "Browse Repositories";
}
};
}
protected JScrollPane createTable() {
pluginsModel = new InstalledPluginsTableModel();
pluginTable = new PluginTable(pluginsModel);
pluginTable.setTableHeader(null);
JScrollPane installedScrollPane = ScrollPaneFactory.createScrollPane(pluginTable);
pluginTable.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final int column = InstalledPluginsTableModel.getCheckboxColumn();
final int[] selectedRows = pluginTable.getSelectedRows();
boolean currentlyMarked = true;
for (final int selectedRow : selectedRows) {
if (selectedRow < 0 || !pluginTable.isCellEditable(selectedRow, column)) {
return;
}
final Boolean enabled = (Boolean)pluginTable.getValueAt(selectedRow, column);
currentlyMarked &= enabled == null || enabled.booleanValue();
}
final IdeaPluginDescriptor[] selected = new IdeaPluginDescriptor[selectedRows.length];
for (int i = 0, selectedLength = selected.length; i < selectedLength; i++) {
selected[i] = pluginsModel.getObjectAt(pluginTable.convertRowIndexToModel(selectedRows[i]));
}
((InstalledPluginsTableModel)pluginsModel).enableRows(selected, currentlyMarked ? Boolean.FALSE : Boolean.TRUE);
pluginTable.repaint();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED);
return installedScrollPane;
}
@Override
protected ActionGroup getActionGroup(boolean inToolbar) {
final DefaultActionGroup actionGroup = new DefaultActionGroup();
actionGroup.add(new RefreshAction());
actionGroup.add(Separator.getInstance());
actionGroup.add(new ActionInstallPlugin(this, this));
actionGroup.add(new ActionUninstallPlugin(this, pluginTable));
if (inToolbar) {
actionGroup.add(new SortByStatusAction("Sort by Status"));
actionGroup.add(new MyFilterEnabledAction());
//actionGroup.add(new MyFilterBundleAction());
}
return actionGroup;
}
@Override
public boolean isModified() {
final boolean modified = super.isModified();
if (modified) return true;
for (int i = 0; i < pluginsModel.getRowCount(); i++) {
final IdeaPluginDescriptor pluginDescriptor = pluginsModel.getObjectAt(i);
if (pluginDescriptor.isEnabled() != ((InstalledPluginsTableModel)pluginsModel).isEnabled(pluginDescriptor.getPluginId())) {
return true;
}
}
for (IdeaPluginDescriptor descriptor : pluginsModel.filtered) {
if (descriptor.isEnabled() !=
((InstalledPluginsTableModel)pluginsModel).isEnabled(descriptor.getPluginId())) {
return true;
}
}
final List<String> disabledPlugins = PluginManagerCore.getDisabledPlugins();
for (Map.Entry<PluginId, Boolean> entry : ((InstalledPluginsTableModel)pluginsModel).getEnabledMap().entrySet()) {
final Boolean enabled = entry.getValue();
if (enabled != null && !enabled.booleanValue() && !disabledPlugins.contains(entry.getKey().toString())) {
return true;
}
}
return false;
}
@Override
public String apply() {
final String apply = super.apply();
if (apply != null) return apply;
for (int i = 0; i < pluginTable.getRowCount(); i++) {
final IdeaPluginDescriptor pluginDescriptor = pluginsModel.getObjectAt(i);
final Boolean enabled = (Boolean)pluginsModel.getValueAt(i, InstalledPluginsTableModel.getCheckboxColumn());
pluginDescriptor.setEnabled(enabled != null && enabled.booleanValue());
}
for (IdeaPluginDescriptor descriptor : pluginsModel.filtered) {
descriptor.setEnabled(
((InstalledPluginsTableModel)pluginsModel).isEnabled(descriptor.getPluginId()));
}
try {
final ArrayList<String> ids = new ArrayList<String>();
for (Map.Entry<PluginId, Boolean> entry : ((InstalledPluginsTableModel)pluginsModel).getEnabledMap().entrySet()) {
final Boolean value = entry.getValue();
if (value != null && !value.booleanValue()) {
ids.add(entry.getKey().getIdString());
}
}
PluginManagerCore.saveDisabledPlugins(ids, false);
}
catch (IOException e) {
LOG.error(e);
}
return null;
}
@Override
protected String canApply() {
final Map<PluginId, Set<PluginId>> dependentToRequiredListMap =
new HashMap<PluginId, Set<PluginId>>(((InstalledPluginsTableModel)pluginsModel).getDependentToRequiredListMap());
for (Iterator<PluginId> iterator = dependentToRequiredListMap.keySet().iterator(); iterator.hasNext(); ) {
final PluginId id = iterator.next();
boolean hasNonModuleDeps = false;
for (PluginId pluginId : dependentToRequiredListMap.get(id)) {
if (!PluginManagerCore.isModuleDependency(pluginId)) {
hasNonModuleDeps = true;
break;
}
}
if (!hasNonModuleDeps) {
iterator.remove();
}
}
if (!dependentToRequiredListMap.isEmpty()) {
return "<html><body style=\"padding: 5px;\">Unable to apply changes: plugin" +
(dependentToRequiredListMap.size() == 1 ? " " : "s ") +
StringUtil.join(dependentToRequiredListMap.keySet(), new Function<PluginId, String>() {
public String fun(final PluginId pluginId) {
final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\"";
}
}, ", ") +
" won't be able to load.</body></html>";
}
return super.canApply();
}
private class MyFilterEnabledAction extends ComboBoxAction implements DumbAware {
@Override
public void update(AnActionEvent e) {
super.update(e);
e.getPresentation().setText(((InstalledPluginsTableModel)pluginsModel).getEnabledFilter());
}
@NotNull
@Override
protected DefaultActionGroup createPopupActionGroup(JComponent button) {
final DefaultActionGroup gr = new DefaultActionGroup();
for (final String enabledValue : InstalledPluginsTableModel.ENABLED_VALUES) {
gr.add(new AnAction(enabledValue) {
@Override
public void actionPerformed(AnActionEvent e) {
final IdeaPluginDescriptor[] selection = pluginTable.getSelectedObjects();
final String filter = myFilter.getFilter().toLowerCase();
((InstalledPluginsTableModel)pluginsModel).setEnabledFilter(enabledValue, filter);
if (selection != null) {
select(selection);
}
}
});
}
return gr;
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
final JComponent component = super.createCustomComponent(presentation);
final JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
panel.add(component, BorderLayout.CENTER);
final JLabel comp = new JLabel("Show:");
comp.setIconTextGap(0);
comp.setHorizontalTextPosition(SwingConstants.RIGHT);
comp.setVerticalTextPosition(SwingConstants.CENTER);
comp.setAlignmentX(Component.RIGHT_ALIGNMENT);
panel.add(comp, BorderLayout.WEST);
panel.setBorder(IdeBorderFactory.createEmptyBorder(0, 2, 0, 0));
return panel;
}
}
private class BrowseRepoListener implements ActionListener {
private final String myVendor;
public BrowseRepoListener(String vendor) {
myVendor = vendor;
}
@Override
public void actionPerformed(ActionEvent e) {
final PluginManagerConfigurable configurable = createAvailableConfigurable(myVendor);
final SingleConfigurableEditor configurableEditor =
new SingleConfigurableEditor(myActionsPanel, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable), false) {
{
setOKButtonText(CommonBundle.message("close.action.name"));
setOKButtonMnemonic('C');
final String filter = myFilter.getFilter();
if (!StringUtil.isEmptyOrSpaces(filter)) {
final Runnable searchRunnable = configurable.enableSearch(filter);
LOG.assertTrue(searchRunnable != null);
searchRunnable.run();
}
}
@NotNull
@Override
protected Action[] createActions() {
return new Action[]{getOKAction()};
}
};
configurableEditor.show();
}
}
}
| platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.plugins;
import com.intellij.CommonBundle;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.ide.startup.StartupActionScriptManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.options.ex.SingleConfigurableEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
/**
* User: anna
*/
public class InstalledPluginsManagerMain extends PluginManagerMain {
public InstalledPluginsManagerMain(PluginManagerUISettings uiSettings) {
super(uiSettings);
init();
myActionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
final JButton jbButton = new JButton("Install JetBrains plugin...");
jbButton.setMnemonic('j');
jbButton.addActionListener(new BrowseRepoListener("JetBrains"));
myActionsPanel.add(jbButton);
final JButton button = new JButton("Browse repositories...");
button.setMnemonic('b');
button.addActionListener(new BrowseRepoListener(null));
myActionsPanel.add(button);
final JButton installPluginFromFileSystem = new JButton("Install plugin from disk...");
installPluginFromFileSystem.setMnemonic('d');
installPluginFromFileSystem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, false){
@Override
public boolean isFileSelectable(VirtualFile file) {
final String extension = file.getExtension();
return Comparing.strEqual(extension, "jar") || Comparing.strEqual(extension, "zip");
}
};
descriptor.setTitle("Choose Plugin File");
descriptor.setDescription("JAR and ZIP archives are accepted");
FileChooser.chooseFiles(descriptor, null, myActionsPanel, null, new FileChooser.FileChooserConsumer() {
@Override
public void cancelled() {
}
@Override
public void consume(List<VirtualFile> files) {
if (files != null && files.size() == 1) {
VirtualFile virtualFile = files.get(0);
if (virtualFile != null) {
final File file = VfsUtilCore.virtualToIoFile(virtualFile);
try {
final IdeaPluginDescriptorImpl pluginDescriptor = PluginDownloader.loadDescriptionFromJar(file);
if (pluginDescriptor == null) {
Messages.showErrorDialog("Fail to load plugin descriptor from file " + file.getName(), CommonBundle.getErrorTitle());
return;
}
if (PluginManager.isIncompatible(pluginDescriptor)) {
Messages.showErrorDialog("Plugin " + pluginDescriptor.getName() + " is incompatible with current installation", CommonBundle.getErrorTitle());
return;
}
final IdeaPluginDescriptor alreadyInstalledPlugin = PluginManager.getPlugin(pluginDescriptor.getPluginId());
if (alreadyInstalledPlugin != null) {
final File oldFile = alreadyInstalledPlugin.getPath();
if (oldFile != null) {
StartupActionScriptManager.addActionCommand(new StartupActionScriptManager.DeleteCommand(oldFile));
}
}
if (((InstalledPluginsTableModel)pluginsModel).appendOrUpdateDescriptor(pluginDescriptor)) {
PluginDownloader.install(file, file.getName(), false);
select(pluginDescriptor);
checkInstalledPluginDependencies(pluginDescriptor);
setRequireShutdown(true);
}
else {
Messages.showInfoMessage(myActionsPanel, "Plugin " + pluginDescriptor.getName() + " was already installed",
CommonBundle.getWarningTitle());
}
}
catch (IOException ex) {
Messages.showErrorDialog(ex.getMessage(), CommonBundle.getErrorTitle());
}
}
}
}
});
}
});
myActionsPanel.add(installPluginFromFileSystem);
}
private void checkInstalledPluginDependencies(IdeaPluginDescriptorImpl pluginDescriptor) {
final Set<PluginId> notInstalled = new HashSet<PluginId>();
final Set<PluginId> disabledIds = new HashSet<PluginId>();
final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds();
for (PluginId id : dependentPluginIds) {
if (ArrayUtil.find(optionalDependentPluginIds, id) > -1) continue;
final boolean disabled = ((InstalledPluginsTableModel)pluginsModel).isDisabled(id);
final boolean enabled = ((InstalledPluginsTableModel)pluginsModel).isEnabled(id);
if (!enabled && !disabled && !PluginManager.isModuleDependency(id)) {
notInstalled.add(id);
} else if (disabled) {
disabledIds.add(id);
}
}
if (!notInstalled.isEmpty()) {
Messages.showWarningDialog("Plugin " +
pluginDescriptor.getName() +
" depends on unknown plugin" +
(notInstalled.size() > 1 ? "s " : " ") +
StringUtil.join(notInstalled, new Function<PluginId, String>() {
@Override
public String fun(PluginId id) {
return id.toString();
}
}, ", "), CommonBundle.getWarningTitle());
}
if (!disabledIds.isEmpty()) {
final Set<IdeaPluginDescriptor> dependencies = new HashSet<IdeaPluginDescriptor>();
for (IdeaPluginDescriptor ideaPluginDescriptor : pluginsModel.view) {
if (disabledIds.contains(ideaPluginDescriptor.getPluginId())) {
dependencies.add(ideaPluginDescriptor);
}
}
final String disabledPluginsMessage = "disabled plugin" + (dependencies.size() > 1 ? "s " : " ");
String message = "Plugin " +
pluginDescriptor.getName() +
" depends on " +
disabledPluginsMessage +
StringUtil.join(dependencies, new Function<IdeaPluginDescriptor, String>() {
@Override
public String fun(IdeaPluginDescriptor ideaPluginDescriptor) {
return ideaPluginDescriptor.getName();
}
}, ", ") +
". Enable " + disabledPluginsMessage.trim() + "?";
if (Messages.showOkCancelDialog(myActionsPanel, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) ==
DialogWrapper.OK_EXIT_CODE) {
((InstalledPluginsTableModel)pluginsModel).enableRows(dependencies.toArray(new IdeaPluginDescriptor[dependencies.size()]), Boolean.TRUE);
}
}
}
@Override
protected void propagateUpdates(List<IdeaPluginDescriptor> list) {
}
private PluginManagerConfigurable createAvailableConfigurable(final String vendorFilter) {
return new PluginManagerConfigurable(PluginManagerUISettings.getInstance(), true) {
@Override
protected PluginManagerMain createPanel() {
return new AvailablePluginsManagerMain(InstalledPluginsManagerMain.this, myUISettings, vendorFilter);
}
@Override
public String getDisplayName() {
return vendorFilter != null ? "Browse " + vendorFilter + " Plugins " : "Browse Repositories";
}
};
}
protected JScrollPane createTable() {
pluginsModel = new InstalledPluginsTableModel();
pluginTable = new PluginTable(pluginsModel);
pluginTable.setTableHeader(null);
JScrollPane installedScrollPane = ScrollPaneFactory.createScrollPane(pluginTable);
pluginTable.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final int column = InstalledPluginsTableModel.getCheckboxColumn();
final int[] selectedRows = pluginTable.getSelectedRows();
boolean currentlyMarked = true;
for (final int selectedRow : selectedRows) {
if (selectedRow < 0 || !pluginTable.isCellEditable(selectedRow, column)) {
return;
}
final Boolean enabled = (Boolean)pluginTable.getValueAt(selectedRow, column);
currentlyMarked &= enabled == null || enabled.booleanValue();
}
final IdeaPluginDescriptor[] selected = new IdeaPluginDescriptor[selectedRows.length];
for (int i = 0, selectedLength = selected.length; i < selectedLength; i++) {
selected[i] = pluginsModel.getObjectAt(pluginTable.convertRowIndexToModel(selectedRows[i]));
}
((InstalledPluginsTableModel)pluginsModel).enableRows(selected, currentlyMarked ? Boolean.FALSE : Boolean.TRUE);
pluginTable.repaint();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED);
return installedScrollPane;
}
@Override
protected ActionGroup getActionGroup(boolean inToolbar) {
final DefaultActionGroup actionGroup = new DefaultActionGroup();
actionGroup.add(new RefreshAction());
actionGroup.add(Separator.getInstance());
actionGroup.add(new ActionInstallPlugin(this, this));
actionGroup.add(new ActionUninstallPlugin(this, pluginTable));
if (inToolbar) {
actionGroup.add(new SortByStatusAction("Sort by Status"));
actionGroup.add(new MyFilterEnabledAction());
//actionGroup.add(new MyFilterBundleAction());
}
return actionGroup;
}
@Override
public boolean isModified() {
final boolean modified = super.isModified();
if (modified) return true;
for (int i = 0; i < pluginsModel.getRowCount(); i++) {
final IdeaPluginDescriptor pluginDescriptor = pluginsModel.getObjectAt(i);
if (pluginDescriptor.isEnabled() != ((InstalledPluginsTableModel)pluginsModel).isEnabled(pluginDescriptor.getPluginId())) {
return true;
}
}
for (IdeaPluginDescriptor descriptor : pluginsModel.filtered) {
if (descriptor.isEnabled() !=
((InstalledPluginsTableModel)pluginsModel).isEnabled(descriptor.getPluginId())) {
return true;
}
}
final List<String> disabledPlugins = PluginManager.getDisabledPlugins();
for (Map.Entry<PluginId, Boolean> entry : ((InstalledPluginsTableModel)pluginsModel).getEnabledMap().entrySet()) {
final Boolean enabled = entry.getValue();
if (enabled != null && !enabled.booleanValue() && !disabledPlugins.contains(entry.getKey().toString())) {
return true;
}
}
return false;
}
@Override
public String apply() {
final String apply = super.apply();
if (apply != null) return apply;
for (int i = 0; i < pluginTable.getRowCount(); i++) {
final IdeaPluginDescriptor pluginDescriptor = pluginsModel.getObjectAt(i);
final Boolean enabled = (Boolean)pluginsModel.getValueAt(i, InstalledPluginsTableModel.getCheckboxColumn());
pluginDescriptor.setEnabled(enabled != null && enabled.booleanValue());
}
for (IdeaPluginDescriptor descriptor : pluginsModel.filtered) {
descriptor.setEnabled(
((InstalledPluginsTableModel)pluginsModel).isEnabled(descriptor.getPluginId()));
}
try {
final ArrayList<String> ids = new ArrayList<String>();
for (Map.Entry<PluginId, Boolean> entry : ((InstalledPluginsTableModel)pluginsModel).getEnabledMap().entrySet()) {
final Boolean value = entry.getValue();
if (value != null && !value.booleanValue()) {
ids.add(entry.getKey().getIdString());
}
}
PluginManager.saveDisabledPlugins(ids, false);
}
catch (IOException e) {
LOG.error(e);
}
return null;
}
@Override
protected String canApply() {
final Map<PluginId, Set<PluginId>> dependentToRequiredListMap =
new HashMap<PluginId, Set<PluginId>>(((InstalledPluginsTableModel)pluginsModel).getDependentToRequiredListMap());
for (Iterator<PluginId> iterator = dependentToRequiredListMap.keySet().iterator(); iterator.hasNext(); ) {
final PluginId id = iterator.next();
boolean hasNonModuleDeps = false;
for (PluginId pluginId : dependentToRequiredListMap.get(id)) {
if (!PluginManager.isModuleDependency(pluginId)) {
hasNonModuleDeps = true;
break;
}
}
if (!hasNonModuleDeps) {
iterator.remove();
}
}
if (!dependentToRequiredListMap.isEmpty()) {
final StringBuffer sb = new StringBuffer("<html><body style=\"padding: 5px;\">Unable to apply changes: plugin")
.append(dependentToRequiredListMap.size() == 1 ? " " : "s ");
sb.append(StringUtil.join(dependentToRequiredListMap.keySet(), new Function<PluginId, String>() {
public String fun(final PluginId pluginId) {
final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\"";
}
}, ", "));
sb.append(" won't be able to load.</body></html>");
return sb.toString();
}
return super.canApply();
}
private class MyFilterEnabledAction extends ComboBoxAction implements DumbAware {
@Override
public void update(AnActionEvent e) {
super.update(e);
e.getPresentation().setText(((InstalledPluginsTableModel)pluginsModel).getEnabledFilter());
}
@NotNull
@Override
protected DefaultActionGroup createPopupActionGroup(JComponent button) {
final DefaultActionGroup gr = new DefaultActionGroup();
for (final String enabledValue : InstalledPluginsTableModel.ENABLED_VALUES) {
gr.add(new AnAction(enabledValue) {
@Override
public void actionPerformed(AnActionEvent e) {
final IdeaPluginDescriptor[] selection = pluginTable.getSelectedObjects();
final String filter = myFilter.getFilter().toLowerCase();
((InstalledPluginsTableModel)pluginsModel).setEnabledFilter(enabledValue, filter);
if (selection != null) {
select(selection);
}
}
});
}
return gr;
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
final JComponent component = super.createCustomComponent(presentation);
final JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
panel.add(component, BorderLayout.CENTER);
final JLabel comp = new JLabel("Show:");
comp.setIconTextGap(0);
comp.setHorizontalTextPosition(SwingConstants.RIGHT);
comp.setVerticalTextPosition(SwingConstants.CENTER);
comp.setAlignmentX(Component.RIGHT_ALIGNMENT);
panel.add(comp, BorderLayout.WEST);
panel.setBorder(IdeBorderFactory.createEmptyBorder(0, 2, 0, 0));
return panel;
}
}
private class BrowseRepoListener implements ActionListener {
private final String myVendor;
public BrowseRepoListener(String vendor) {
myVendor = vendor;
}
@Override
public void actionPerformed(ActionEvent e) {
final PluginManagerConfigurable configurable = createAvailableConfigurable(myVendor);
final SingleConfigurableEditor configurableEditor =
new SingleConfigurableEditor(myActionsPanel, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable), false) {
{
setOKButtonText(CommonBundle.message("close.action.name"));
setOKButtonMnemonic('C');
}
@NotNull
@Override
protected Action[] createActions() {
return new Action[]{getOKAction()};
}
};
configurableEditor.show();
}
}
}
| plugins search: filter plugin repository when installed plugins were filtered; suggest to browse repository when nothing found in installed (IDEA-107660)
| platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java | plugins search: filter plugin repository when installed plugins were filtered; suggest to browse repository when nothing found in installed (IDEA-107660) | <ide><path>latform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java
<ide> import com.intellij.openapi.vfs.VirtualFile;
<ide> import com.intellij.ui.IdeBorderFactory;
<ide> import com.intellij.ui.ScrollPaneFactory;
<del>import com.intellij.util.ArrayUtil;
<add>import com.intellij.ui.SimpleTextAttributes;
<add>import com.intellij.util.ArrayUtilRt;
<ide> import com.intellij.util.Function;
<add>import com.intellij.util.ui.StatusText;
<ide> import org.jetbrains.annotations.NotNull;
<ide>
<ide> import javax.swing.*;
<ide> Messages.showErrorDialog("Fail to load plugin descriptor from file " + file.getName(), CommonBundle.getErrorTitle());
<ide> return;
<ide> }
<del> if (PluginManager.isIncompatible(pluginDescriptor)) {
<add> if (PluginManagerCore.isIncompatible(pluginDescriptor)) {
<ide> Messages.showErrorDialog("Plugin " + pluginDescriptor.getName() + " is incompatible with current installation", CommonBundle.getErrorTitle());
<ide> return;
<ide> }
<ide> }
<ide> });
<ide> myActionsPanel.add(installPluginFromFileSystem);
<add> final StatusText emptyText = pluginTable.getEmptyText();
<add> emptyText.setText("Nothing to show.");
<add> emptyText.appendText(" Click ");
<add> emptyText.appendText("Browse", SimpleTextAttributes.LINK_ATTRIBUTES, new BrowseRepoListener(null));
<add> emptyText.appendText(" to search for non-bundled plugins.");
<ide> }
<ide>
<ide> private void checkInstalledPluginDependencies(IdeaPluginDescriptorImpl pluginDescriptor) {
<ide> final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
<ide> final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds();
<ide> for (PluginId id : dependentPluginIds) {
<del> if (ArrayUtil.find(optionalDependentPluginIds, id) > -1) continue;
<add> if (ArrayUtilRt.find(optionalDependentPluginIds, id) > -1) continue;
<ide> final boolean disabled = ((InstalledPluginsTableModel)pluginsModel).isDisabled(id);
<ide> final boolean enabled = ((InstalledPluginsTableModel)pluginsModel).isEnabled(id);
<del> if (!enabled && !disabled && !PluginManager.isModuleDependency(id)) {
<add> if (!enabled && !disabled && !PluginManagerCore.isModuleDependency(id)) {
<ide> notInstalled.add(id);
<ide> } else if (disabled) {
<ide> disabledIds.add(id);
<ide> return true;
<ide> }
<ide> }
<del> final List<String> disabledPlugins = PluginManager.getDisabledPlugins();
<add> final List<String> disabledPlugins = PluginManagerCore.getDisabledPlugins();
<ide> for (Map.Entry<PluginId, Boolean> entry : ((InstalledPluginsTableModel)pluginsModel).getEnabledMap().entrySet()) {
<ide> final Boolean enabled = entry.getValue();
<ide> if (enabled != null && !enabled.booleanValue() && !disabledPlugins.contains(entry.getKey().toString())) {
<ide> ids.add(entry.getKey().getIdString());
<ide> }
<ide> }
<del> PluginManager.saveDisabledPlugins(ids, false);
<add> PluginManagerCore.saveDisabledPlugins(ids, false);
<ide> }
<ide> catch (IOException e) {
<ide> LOG.error(e);
<ide> final PluginId id = iterator.next();
<ide> boolean hasNonModuleDeps = false;
<ide> for (PluginId pluginId : dependentToRequiredListMap.get(id)) {
<del> if (!PluginManager.isModuleDependency(pluginId)) {
<add> if (!PluginManagerCore.isModuleDependency(pluginId)) {
<ide> hasNonModuleDeps = true;
<ide> break;
<ide> }
<ide> }
<ide> }
<ide> if (!dependentToRequiredListMap.isEmpty()) {
<del> final StringBuffer sb = new StringBuffer("<html><body style=\"padding: 5px;\">Unable to apply changes: plugin")
<del> .append(dependentToRequiredListMap.size() == 1 ? " " : "s ");
<del> sb.append(StringUtil.join(dependentToRequiredListMap.keySet(), new Function<PluginId, String>() {
<del> public String fun(final PluginId pluginId) {
<del> final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
<del> return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\"";
<del> }
<del> }, ", "));
<del> sb.append(" won't be able to load.</body></html>");
<del> return sb.toString();
<add> return "<html><body style=\"padding: 5px;\">Unable to apply changes: plugin" +
<add> (dependentToRequiredListMap.size() == 1 ? " " : "s ") +
<add> StringUtil.join(dependentToRequiredListMap.keySet(), new Function<PluginId, String>() {
<add> public String fun(final PluginId pluginId) {
<add> final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
<add> return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\"";
<add> }
<add> }, ", ") +
<add> " won't be able to load.</body></html>";
<ide> }
<ide> return super.canApply();
<ide> }
<ide> {
<ide> setOKButtonText(CommonBundle.message("close.action.name"));
<ide> setOKButtonMnemonic('C');
<add> final String filter = myFilter.getFilter();
<add> if (!StringUtil.isEmptyOrSpaces(filter)) {
<add> final Runnable searchRunnable = configurable.enableSearch(filter);
<add> LOG.assertTrue(searchRunnable != null);
<add> searchRunnable.run();
<add> }
<ide> }
<ide>
<ide> @NotNull |
|
Java | apache-2.0 | e314562090bc25b60de5c8a1833c33eb99e610ab | 0 | ryano144/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,xfournet/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,nicolargo/intellij-community,caot/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,semonte/intellij-community,slisson/intellij-community,vladmm/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,allotria/intellij-community,signed/intellij-community,Distrotech/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,caot/intellij-community,petteyg/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,clumsy/intellij-community,xfournet/intellij-community,robovm/robovm-studio,supersven/intellij-community,holmes/intellij-community,orekyuu/intellij-community,signed/intellij-community,amith01994/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,semonte/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,semonte/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,semonte/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,samthor/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,holmes/intellij-community,semonte/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,samthor/intellij-community,signed/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,samthor/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,hurricup/intellij-community,signed/intellij-community,caot/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,suncycheng/intellij-community,ibinti/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,asedunov/intellij-community,dslomov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,allotria/intellij-community,kool79/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,caot/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,dslomov/intellij-community,semonte/intellij-community,holmes/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,kool79/intellij-community,signed/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,adedayo/intellij-community,supersven/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ibinti/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,petteyg/intellij-community,dslomov/intellij-community,da1z/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,izonder/intellij-community,wreckJ/intellij-community,holmes/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,fitermay/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,amith01994/intellij-community,kool79/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,samthor/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,signed/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,xfournet/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,kdwink/intellij-community,xfournet/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,caot/intellij-community,izonder/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,asedunov/intellij-community,amith01994/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,izonder/intellij-community,holmes/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,caot/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,samthor/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,da1z/intellij-community,vladmm/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,supersven/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,clumsy/intellij-community,signed/intellij-community,vladmm/intellij-community,supersven/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,blademainer/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ryano144/intellij-community,blademainer/intellij-community,clumsy/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ibinti/intellij-community,fnouama/intellij-community,holmes/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,vladmm/intellij-community,slisson/intellij-community,dslomov/intellij-community,holmes/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,kool79/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,hurricup/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kool79/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,jagguli/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,supersven/intellij-community,allotria/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,samthor/intellij-community,akosyakov/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,slisson/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,adedayo/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,kdwink/intellij-community,kool79/intellij-community,diorcety/intellij-community,holmes/intellij-community,vladmm/intellij-community,asedunov/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,signed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,samthor/intellij-community,da1z/intellij-community,jagguli/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,caot/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,FHannes/intellij-community,slisson/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,slisson/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,ibinti/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,da1z/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,vladmm/intellij-community,jagguli/intellij-community,fitermay/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,dslomov/intellij-community,xfournet/intellij-community,kool79/intellij-community,ahb0327/intellij-community,allotria/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,blademainer/intellij-community,izonder/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,retomerz/intellij-community,vvv1559/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.newvfs.persistent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.util.LowMemoryWatcher;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.*;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.openapi.vfs.newvfs.*;
import com.intellij.openapi.vfs.newvfs.events.*;
import com.intellij.openapi.vfs.newvfs.impl.*;
import com.intellij.util.*;
import com.intellij.util.containers.ConcurrentIntObjectMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.EmptyIntHashSet;
import com.intellij.util.io.ReplicatorInputStream;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import gnu.trove.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author max
*/
public class PersistentFSImpl extends PersistentFS implements ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.persistent.PersistentFS");
private final MessageBus myEventBus;
private final ReadWriteLock myRootsLock = new ReentrantReadWriteLock();
private final Map<String, VirtualFileSystemEntry> myRoots = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
private final TIntObjectHashMap<VirtualFileSystemEntry> myRootsById = new TIntObjectHashMap<VirtualFileSystemEntry>();
private final ConcurrentIntObjectMap<VirtualFileSystemEntry> myIdToDirCache = ContainerUtil.createConcurrentIntObjectMap();
private final Object myInputLock = new Object();
private final AtomicBoolean myShutDown = new AtomicBoolean(false);
@SuppressWarnings("FieldCanBeLocal")
private final LowMemoryWatcher myWatcher = LowMemoryWatcher.register(new Runnable() {
@Override
public void run() {
clearIdCache();
}
});
public PersistentFSImpl(@NotNull MessageBus bus) {
myEventBus = bus;
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override
public void run() {
performShutdown();
}
});
}
@Override
public void initComponent() {
FSRecords.connect();
}
@Override
public void disposeComponent() {
performShutdown();
}
private void performShutdown() {
if (myShutDown.compareAndSet(false, true)) {
LOG.info("VFS dispose started");
FSRecords.dispose();
LOG.info("VFS dispose completed");
}
}
@Override
@NonNls
@NotNull
public String getComponentName() {
return "app.component.PersistentFS";
}
@Override
public boolean areChildrenLoaded(@NotNull final VirtualFile dir) {
return areChildrenLoaded(getFileId(dir));
}
@Override
public long getCreationTimestamp() {
return FSRecords.getCreationTimestamp();
}
@NotNull
private static NewVirtualFileSystem getDelegate(@NotNull VirtualFile file) {
return (NewVirtualFileSystem)file.getFileSystem();
}
@Override
public boolean wereChildrenAccessed(@NotNull final VirtualFile dir) {
return FSRecords.wereChildrenAccessed(getFileId(dir));
}
@Override
@NotNull
public String[] list(@NotNull final VirtualFile file) {
int id = getFileId(file);
FSRecords.NameId[] nameIds = FSRecords.listAll(id);
if (!areChildrenLoaded(id)) {
nameIds = persistAllChildren(file, id, nameIds);
}
return ContainerUtil.map2Array(nameIds, String.class, new Function<FSRecords.NameId, String>() {
@Override
public String fun(FSRecords.NameId id) {
return id.name.toString();
}
});
}
@Override
@NotNull
public String[] listPersisted(@NotNull VirtualFile parent) {
return listPersisted(FSRecords.list(getFileId(parent)));
}
@NotNull
private static String[] listPersisted(@NotNull int[] childrenIds) {
String[] names = ArrayUtil.newStringArray(childrenIds.length);
for (int i = 0; i < childrenIds.length; i++) {
names[i] = FSRecords.getName(childrenIds[i]);
}
return names;
}
@NotNull
private static FSRecords.NameId[] persistAllChildren(@NotNull final VirtualFile file, final int id, @NotNull FSRecords.NameId[] current) {
final NewVirtualFileSystem fs = replaceWithNativeFS(getDelegate(file));
String[] delegateNames = VfsUtil.filterNames(fs.list(file));
if (delegateNames.length == 0 && current.length > 0) {
return current;
}
Set<String> toAdd = ContainerUtil.newHashSet(delegateNames);
for (FSRecords.NameId nameId : current) {
toAdd.remove(nameId.name.toString());
}
final TIntArrayList childrenIds = new TIntArrayList(current.length + toAdd.size());
final List<FSRecords.NameId> nameIds = ContainerUtil.newArrayListWithCapacity(current.length + toAdd.size());
for (FSRecords.NameId nameId : current) {
childrenIds.add(nameId.id);
nameIds.add(nameId);
}
for (String newName : toAdd) {
FakeVirtualFile child = new FakeVirtualFile(file, newName);
FileAttributes attributes = fs.getAttributes(child);
if (attributes != null) {
int childId = createAndFillRecord(fs, child, id, attributes);
childrenIds.add(childId);
nameIds.add(new FSRecords.NameId(childId, FileNameCache.storeName(newName), newName));
}
}
FSRecords.updateList(id, childrenIds.toNativeArray());
setChildrenCached(id);
return nameIds.toArray(new FSRecords.NameId[nameIds.size()]);
}
public static void setChildrenCached(int id) {
int flags = FSRecords.getFlags(id);
FSRecords.setFlags(id, flags | CHILDREN_CACHED_FLAG, true);
}
@Override
@NotNull
public FSRecords.NameId[] listAll(@NotNull VirtualFile parent) {
final int parentId = getFileId(parent);
FSRecords.NameId[] nameIds = FSRecords.listAll(parentId);
if (!areChildrenLoaded(parentId)) {
return persistAllChildren(parent, parentId, nameIds);
}
return nameIds;
}
private static boolean areChildrenLoaded(final int parentId) {
return (FSRecords.getFlags(parentId) & CHILDREN_CACHED_FLAG) != 0;
}
@Override
@Nullable
public DataInputStream readAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) {
return FSRecords.readAttributeWithLock(getFileId(file), att);
}
@Override
@NotNull
public DataOutputStream writeAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) {
return FSRecords.writeAttribute(getFileId(file), att);
}
@Nullable
private static DataInputStream readContent(@NotNull VirtualFile file) {
return FSRecords.readContent(getFileId(file));
}
@Nullable
private static DataInputStream readContentById(int contentId) {
return FSRecords.readContentById(contentId);
}
@NotNull
private static DataOutputStream writeContent(@NotNull VirtualFile file, boolean readOnly) {
return FSRecords.writeContent(getFileId(file), readOnly);
}
private static void writeContent(@NotNull VirtualFile file, ByteSequence content, boolean readOnly) throws IOException {
FSRecords.writeContent(getFileId(file), content, readOnly);
}
@Override
public int storeUnlinkedContent(@NotNull byte[] bytes) {
return FSRecords.storeUnlinkedContent(bytes);
}
@Override
public int getModificationCount(@NotNull final VirtualFile file) {
return FSRecords.getModCount(getFileId(file));
}
@Override
public int getCheapFileSystemModificationCount() {
return FSRecords.getLocalModCount();
}
@Override
public int getFilesystemModificationCount() {
return FSRecords.getModCount();
}
private static boolean writeAttributesToRecord(final int id,
final int parentId,
@NotNull VirtualFile file,
@NotNull NewVirtualFileSystem fs,
@NotNull FileAttributes attributes) {
String name = file.getName();
if (!name.isEmpty()) {
if (namesEqual(fs, name, FSRecords.getName(id))) return false; // TODO: Handle root attributes change.
}
else {
if (areChildrenLoaded(id)) return false; // TODO: hack
}
FSRecords.writeAttributesToRecord(id, parentId, attributes, name);
return true;
}
@Override
public int getFileAttributes(int id) {
assert id > 0;
//noinspection MagicConstant
return FSRecords.getFlags(id);
}
@Override
public boolean isDirectory(@NotNull final VirtualFile file) {
return isDirectory(getFileAttributes(getFileId(file)));
}
private static int getParent(final int id) {
assert id > 0;
return FSRecords.getParent(id);
}
private static boolean namesEqual(@NotNull VirtualFileSystem fs, @NotNull String n1, String n2) {
return fs.isCaseSensitive() ? n1.equals(n2) : n1.equalsIgnoreCase(n2);
}
@Override
public boolean exists(@NotNull final VirtualFile fileOrDirectory) {
return ((VirtualFileWithId)fileOrDirectory).getId() > 0;
}
@Override
public long getTimeStamp(@NotNull final VirtualFile file) {
return FSRecords.getTimestamp(getFileId(file));
}
@Override
public void setTimeStamp(@NotNull final VirtualFile file, final long modStamp) throws IOException {
final int id = getFileId(file);
FSRecords.setTimestamp(id, modStamp);
getDelegate(file).setTimeStamp(file, modStamp);
}
private static int getFileId(@NotNull VirtualFile file) {
final int id = ((VirtualFileWithId)file).getId();
if (id <= 0) {
throw new InvalidVirtualFileAccessException(file);
}
return id;
}
@Override
public boolean isSymLink(@NotNull VirtualFile file) {
return isSymLink(getFileAttributes(getFileId(file)));
}
@Override
public String resolveSymLink(@NotNull VirtualFile file) {
throw new UnsupportedOperationException();
}
@Override
public boolean isSpecialFile(@NotNull VirtualFile file) {
return isSpecialFile(getFileAttributes(getFileId(file)));
}
@Override
public boolean isWritable(@NotNull VirtualFile file) {
return (getFileAttributes(getFileId(file)) & IS_READ_ONLY) == 0;
}
@Override
public boolean isHidden(@NotNull VirtualFile file) {
return (getFileAttributes(getFileId(file)) & IS_HIDDEN) != 0;
}
@Override
public void setWritable(@NotNull final VirtualFile file, final boolean writableFlag) throws IOException {
getDelegate(file).setWritable(file, writableFlag);
boolean oldWritable = isWritable(file);
if (oldWritable != writableFlag) {
processEvent(new VFilePropertyChangeEvent(this, file, VirtualFile.PROP_WRITABLE, oldWritable, writableFlag, false));
}
}
@Override
public int getId(@NotNull VirtualFile parent, @NotNull String childName, @NotNull NewVirtualFileSystem fs) {
int parentId = getFileId(parent);
int[] children = FSRecords.list(parentId);
if (children.length > 0) {
// fast path, check that some child has same nameId as given name, this avoid O(N) on retrieving names for processing non-cached children
int nameId = FSRecords.getNameId(childName);
for (final int childId : children) {
if (nameId == FSRecords.getNameId(childId)) {
return childId;
}
}
// for case sensitive system the above check is exhaustive in consistent state of vfs
}
for (final int childId : children) {
if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId;
}
final VirtualFile fake = new FakeVirtualFile(parent, childName);
final FileAttributes attributes = fs.getAttributes(fake);
if (attributes != null) {
final int child = createAndFillRecord(fs, fake, parentId, attributes);
FSRecords.updateList(parentId, ArrayUtil.append(children, child));
return child;
}
return 0;
}
@Override
public long getLength(@NotNull final VirtualFile file) {
long len;
if (mustReloadContent(file)) {
len = reloadLengthFromDelegate(file, getDelegate(file));
}
else {
final int id = getFileId(file);
len = FSRecords.getLength(id);
}
return len;
}
@NotNull
@Override
public VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile parent, @NotNull String name) throws IOException {
getDelegate(file).copyFile(requestor, file, parent, name);
processEvent(new VFileCopyEvent(requestor, file, parent, name));
final VirtualFile child = parent.findChild(name);
if (child == null) {
throw new IOException("Cannot create child");
}
return child;
}
@NotNull
@Override
public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException {
getDelegate(parent).createChildDirectory(requestor, parent, dir);
processEvent(new VFileCreateEvent(requestor, parent, dir, true, false));
final VirtualFile child = parent.findChild(dir);
if (child == null) {
throw new IOException("Cannot create child directory '" + dir + "' at " + parent.getPath());
}
return child;
}
@NotNull
@Override
public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
getDelegate(parent).createChildFile(requestor, parent, file);
processEvent(new VFileCreateEvent(requestor, parent, file, false, false));
final VirtualFile child = parent.findChild(file);
if (child == null) {
throw new IOException("Cannot create child file '" + file + "' at " + parent.getPath());
}
return child;
}
@Override
public void deleteFile(final Object requestor, @NotNull final VirtualFile file) throws IOException {
final NewVirtualFileSystem delegate = getDelegate(file);
delegate.deleteFile(requestor, file);
if (!delegate.exists(file)) {
processEvent(new VFileDeleteEvent(requestor, file, false));
}
}
@Override
public void renameFile(final Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException {
getDelegate(file).renameFile(requestor, file, newName);
String oldName = file.getName();
if (!newName.equals(oldName)) {
processEvent(new VFilePropertyChangeEvent(requestor, file, VirtualFile.PROP_NAME, oldName, newName, false));
}
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {
return contentsToByteArray(file, true);
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file, boolean cacheContent) throws IOException {
InputStream contentStream = null;
boolean reloadFromDelegate;
boolean outdated;
int fileId;
synchronized (myInputLock) {
fileId = getFileId(file);
outdated = checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L;
reloadFromDelegate = outdated || (contentStream = readContent(file)) == null;
}
if (reloadFromDelegate) {
final NewVirtualFileSystem delegate = getDelegate(file);
final byte[] content;
if (outdated) {
// in this case, file can have out-of-date length. so, update it first (it's needed for correct contentsToByteArray() work)
// see IDEA-90813 for possible bugs
FSRecords.setLength(fileId, delegate.getLength(file));
content = delegate.contentsToByteArray(file);
}
else {
// a bit of optimization
content = delegate.contentsToByteArray(file);
FSRecords.setLength(fileId, content.length);
}
ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
// we should cache every local files content
// because the local history feature is currently depends on this cache,
// perforce offline mode as well
if ((!delegate.isReadOnly() ||
// do not cache archive content unless asked
cacheContent && !application.isInternal() && !application.isUnitTestMode()) &&
content.length <= PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) {
synchronized (myInputLock) {
writeContent(file, new ByteSequence(content), delegate.isReadOnly());
setFlag(file, MUST_RELOAD_CONTENT, false);
}
}
return content;
}
else {
try {
final int length = (int)file.getLength();
assert length >= 0 : file;
return FileUtil.loadBytes(contentStream, length);
}
catch (IOException e) {
throw FSRecords.handleError(e);
}
}
}
@Override
@NotNull
public byte[] contentsToByteArray(int contentId) throws IOException {
final DataInputStream stream = readContentById(contentId);
assert stream != null : contentId;
return FileUtil.loadBytes(stream);
}
@Override
@NotNull
public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {
synchronized (myInputLock) {
InputStream contentStream;
if (mustReloadContent(file) || (contentStream = readContent(file)) == null) {
NewVirtualFileSystem delegate = getDelegate(file);
long len = reloadLengthFromDelegate(file, delegate);
InputStream nativeStream = delegate.getInputStream(file);
if (len > PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) return nativeStream;
return createReplicator(file, nativeStream, len, delegate.isReadOnly());
}
else {
return contentStream;
}
}
}
private static long reloadLengthFromDelegate(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem delegate) {
final long len = delegate.getLength(file);
FSRecords.setLength(getFileId(file), len);
return len;
}
private InputStream createReplicator(@NotNull final VirtualFile file,
final InputStream nativeStream,
final long fileLength,
final boolean readOnly) throws IOException {
if (nativeStream instanceof BufferExposingByteArrayInputStream) {
// optimization
BufferExposingByteArrayInputStream byteStream = (BufferExposingByteArrayInputStream )nativeStream;
byte[] bytes = byteStream.getInternalBuffer();
storeContentToStorage(fileLength, file, readOnly, bytes, bytes.length);
return nativeStream;
}
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
final BufferExposingByteArrayOutputStream cache = new BufferExposingByteArrayOutputStream((int)fileLength);
return new ReplicatorInputStream(nativeStream, cache) {
@Override
public void close() throws IOException {
super.close();
storeContentToStorage(fileLength, file, readOnly, cache.getInternalBuffer(), cache.size());
}
};
}
private void storeContentToStorage(long fileLength,
@NotNull VirtualFile file,
boolean readOnly, @NotNull byte[] bytes, int bytesLength)
throws IOException {
synchronized (myInputLock) {
if (bytesLength == fileLength) {
writeContent(file, new ByteSequence(bytes, 0, bytesLength), readOnly);
setFlag(file, MUST_RELOAD_CONTENT, false);
}
else {
setFlag(file, MUST_RELOAD_CONTENT, true);
}
}
}
private static boolean mustReloadContent(@NotNull VirtualFile file) {
int fileId = getFileId(file);
return checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L;
}
@Override
@NotNull
public OutputStream getOutputStream(@NotNull final VirtualFile file,
final Object requestor,
final long modStamp,
final long timeStamp) throws IOException {
return new ByteArrayOutputStream() {
private boolean closed; // protection against user calling .close() twice
@Override
public void close() throws IOException {
if (closed) return;
super.close();
ApplicationManager.getApplication().assertWriteAccessAllowed();
VFileContentChangeEvent event = new VFileContentChangeEvent(requestor, file, file.getModificationStamp(), modStamp, false);
List<VFileContentChangeEvent> events = Collections.singletonList(event);
BulkFileListener publisher = myEventBus.syncPublisher(VirtualFileManager.VFS_CHANGES);
publisher.before(events);
NewVirtualFileSystem delegate = getDelegate(file);
OutputStream ioFileStream = delegate.getOutputStream(file, requestor, modStamp, timeStamp);
// FSRecords.ContentOutputStream already buffered, no need to wrap in BufferedStream
OutputStream persistenceStream = writeContent(file, delegate.isReadOnly());
try {
persistenceStream.write(buf, 0, count);
}
finally {
try {
ioFileStream.write(buf, 0, count);
}
finally {
closed = true;
persistenceStream.close();
ioFileStream.close();
executeTouch(file, false, event.getModificationStamp());
publisher.after(events);
}
}
}
};
}
@Override
public int acquireContent(@NotNull VirtualFile file) {
return FSRecords.acquireFileContent(getFileId(file));
}
@Override
public void releaseContent(int contentId) {
FSRecords.releaseContent(contentId);
}
@Override
public int getCurrentContentId(@NotNull VirtualFile file) {
return FSRecords.getContentId(getFileId(file));
}
@Override
public void moveFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent) throws IOException {
getDelegate(file).moveFile(requestor, file, newParent);
processEvent(new VFileMoveEvent(requestor, file, newParent));
}
private void processEvent(@NotNull VFileEvent event) {
processEvents(Collections.singletonList(event));
}
private static class EventWrapper {
private final VFileDeleteEvent event;
private final int id;
private EventWrapper(final VFileDeleteEvent event, final int id) {
this.event = event;
this.id = id;
}
}
@NotNull private static final Comparator<EventWrapper> DEPTH_COMPARATOR = new Comparator<EventWrapper>() {
@Override
public int compare(@NotNull final EventWrapper o1, @NotNull final EventWrapper o2) {
return o1.event.getFileDepth() - o2.event.getFileDepth();
}
};
@NotNull
private static List<VFileEvent> validateEvents(@NotNull List<VFileEvent> events) {
final List<EventWrapper> deletionEvents = ContainerUtil.newArrayList();
for (int i = 0, size = events.size(); i < size; i++) {
final VFileEvent event = events.get(i);
if (event instanceof VFileDeleteEvent && event.isValid()) {
deletionEvents.add(new EventWrapper((VFileDeleteEvent)event, i));
}
}
final TIntHashSet invalidIDs;
if (deletionEvents.isEmpty()) {
invalidIDs = EmptyIntHashSet.INSTANCE;
}
else {
ContainerUtil.quickSort(deletionEvents, DEPTH_COMPARATOR);
invalidIDs = new TIntHashSet(deletionEvents.size());
final Set<VirtualFile> dirsToBeDeleted = new THashSet<VirtualFile>(deletionEvents.size());
nextEvent:
for (EventWrapper wrapper : deletionEvents) {
final VirtualFile candidate = wrapper.event.getFile();
VirtualFile parent = candidate;
while (parent != null) {
if (dirsToBeDeleted.contains(parent)) {
invalidIDs.add(wrapper.id);
continue nextEvent;
}
parent = parent.getParent();
}
if (candidate.isDirectory()) {
dirsToBeDeleted.add(candidate);
}
}
}
final List<VFileEvent> filtered = new ArrayList<VFileEvent>(events.size() - invalidIDs.size());
for (int i = 0, size = events.size(); i < size; i++) {
final VFileEvent event = events.get(i);
if (event.isValid() && !(event instanceof VFileDeleteEvent && invalidIDs.contains(i))) {
filtered.add(event);
}
}
return filtered;
}
@Override
public void processEvents(@NotNull List<VFileEvent> events) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
List<VFileEvent> validated = validateEvents(events);
BulkFileListener publisher = myEventBus.syncPublisher(VirtualFileManager.VFS_CHANGES);
publisher.before(validated);
THashMap<VirtualFile, List<VFileEvent>> parentToChildrenEventsChanges = null;
for (VFileEvent event : validated) {
VirtualFile changedParent = null;
if (event instanceof VFileCreateEvent) {
changedParent = ((VFileCreateEvent)event).getParent();
((VFileCreateEvent)event).resetCache();
}
else if (event instanceof VFileDeleteEvent) {
changedParent = ((VFileDeleteEvent)event).getFile().getParent();
}
if (changedParent != null) {
if (parentToChildrenEventsChanges == null) parentToChildrenEventsChanges = new THashMap<VirtualFile, List<VFileEvent>>();
List<VFileEvent> parentChildrenChanges = parentToChildrenEventsChanges.get(changedParent);
if (parentChildrenChanges == null) {
parentToChildrenEventsChanges.put(changedParent, parentChildrenChanges = new SmartList<VFileEvent>());
}
parentChildrenChanges.add(event);
}
else {
applyEvent(event);
}
}
if (parentToChildrenEventsChanges != null) {
parentToChildrenEventsChanges.forEachEntry(new TObjectObjectProcedure<VirtualFile, List<VFileEvent>>() {
@Override
public boolean execute(VirtualFile parent, List<VFileEvent> childrenEvents) {
applyChildrenChangeEvents(parent, childrenEvents);
return true;
}
});
parentToChildrenEventsChanges.clear();
}
publisher.after(validated);
}
private void applyChildrenChangeEvents(VirtualFile parent, List<VFileEvent> events) {
final NewVirtualFileSystem delegate = getDelegate(parent);
TIntArrayList childrenIdsUpdated = new TIntArrayList();
List<VirtualFile> childrenToBeUpdated = new SmartList<VirtualFile>();
final int parentId = getFileId(parent);
assert parentId != 0;
TIntHashSet parentChildrenIds = new TIntHashSet(FSRecords.list(parentId));
boolean hasRemovedChildren = false;
for (VFileEvent event : events) {
if (event instanceof VFileCreateEvent) {
String name = ((VFileCreateEvent)event).getChildName();
final VirtualFile fake = new FakeVirtualFile(parent, name);
final FileAttributes attributes = delegate.getAttributes(fake);
if (attributes != null) {
final int childId = createAndFillRecord(delegate, fake, parentId, attributes);
assert parent instanceof VirtualDirectoryImpl : parent;
final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent;
VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem());
childrenToBeUpdated.add(child);
childrenIdsUpdated.add(childId);
parentChildrenIds.add(childId);
}
}
else if (event instanceof VFileDeleteEvent) {
VirtualFile file = ((VFileDeleteEvent)event).getFile();
if (!file.exists()) {
LOG.error("Deleting a file, which does not exist: " + file.getPath());
continue;
}
hasRemovedChildren = true;
int id = getFileId(file);
childrenToBeUpdated.add(file);
childrenIdsUpdated.add(-id);
parentChildrenIds.remove(id);
}
}
FSRecords.updateList(parentId, parentChildrenIds.toArray());
if (hasRemovedChildren) clearIdCache();
VirtualDirectoryImpl parentImpl = (VirtualDirectoryImpl)parent;
for (int i = 0, len = childrenIdsUpdated.size(); i < len; ++i) {
final int childId = childrenIdsUpdated.get(i);
final VirtualFile childFile = childrenToBeUpdated.get(i);
if (childId > 0) {
parentImpl.addChild((VirtualFileSystemEntry)childFile);
}
else {
FSRecords.deleteRecordRecursively(-childId);
parentImpl.removeChild(childFile);
invalidateSubtree(childFile);
}
}
}
@Override
@Nullable
public VirtualFileSystemEntry findRoot(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) {
if (basePath.isEmpty()) {
LOG.error("Invalid root, fs=" + fs);
return null;
}
String rootUrl = normalizeRootUrl(basePath, fs);
myRootsLock.readLock().lock();
try {
VirtualFileSystemEntry root = myRoots.get(rootUrl);
if (root != null) return root;
}
finally {
myRootsLock.readLock().unlock();
}
final VirtualFileSystemEntry newRoot;
int rootId = FSRecords.findRootRecord(rootUrl);
VfsData.Segment segment = VfsData.getSegment(rootId, true);
VfsData.DirectoryData directoryData = new VfsData.DirectoryData();
if (fs instanceof JarFileSystem) {
String parentPath = basePath.substring(0, basePath.indexOf(JarFileSystem.JAR_SEPARATOR));
VirtualFile parentFile = LocalFileSystem.getInstance().findFileByPath(parentPath);
if (parentFile == null) return null;
FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(parentFile.getName());
if (type != FileTypes.ARCHIVE) return null;
newRoot = new JarRoot(fs, rootId, segment, directoryData, parentFile);
}
else {
newRoot = new FsRoot(fs, rootId, segment, directoryData, basePath);
}
FileAttributes attributes = fs.getAttributes(new StubVirtualFile() {
@NotNull
@Override
public String getPath() {
return newRoot.getPath();
}
@Nullable
@Override
public VirtualFile getParent() {
return null;
}
});
if (attributes == null || !attributes.isDirectory()) {
return null;
}
boolean mark = false;
myRootsLock.writeLock().lock();
try {
VirtualFileSystemEntry root = myRoots.get(rootUrl);
if (root != null) return root;
VfsData.initFile(rootId, segment, -1, directoryData);
mark = writeAttributesToRecord(rootId, 0, newRoot, fs, attributes);
myRoots.put(rootUrl, newRoot);
myRootsById.put(rootId, newRoot);
}
finally {
myRootsLock.writeLock().unlock();
}
if (!mark && attributes.lastModified != FSRecords.getTimestamp(rootId)) {
newRoot.markDirtyRecursively();
}
LOG.assertTrue(rootId == newRoot.getId(), "root=" + newRoot + " expected=" + rootId + " actual=" + newRoot.getId());
return newRoot;
}
@NotNull
private static String normalizeRootUrl(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) {
// need to protect against relative path of the form "/x/../y"
return UriUtil.trimTrailingSlashes(
fs.getProtocol() + URLUtil.SCHEME_SEPARATOR + VfsImplUtil.normalize(fs, FileUtil.toCanonicalPath(basePath)));
}
@Override
public void clearIdCache() {
myIdToDirCache.clear();
}
private static final int DEPTH_LIMIT = 75;
@Override
@Nullable
public NewVirtualFile findFileById(final int id) {
return findFileById(id, false, null, 0);
}
@Override
public NewVirtualFile findFileByIdIfCached(final int id) {
return findFileById(id, true, null, 0);
}
@Nullable
private VirtualFileSystemEntry findFileById(int id, boolean cachedOnly, TIntArrayList visited, int mask) {
VirtualFileSystemEntry cached = myIdToDirCache.get(id);
if (cached != null) return cached;
if (visited != null && (visited.size() >= DEPTH_LIMIT || (mask & id) == id && visited.contains(id))) {
@NonNls String sb = "Dead loop detected in persistent FS (id=" + id + " cached-only=" + cachedOnly + "):";
for (int i = 0; i < visited.size(); i++) {
int _id = visited.get(i);
sb += "\n " + _id + " '" + getName(_id) + "' " +
String.format("%02x", getFileAttributes(_id)) + ' ' + myIdToDirCache.containsKey(_id);
}
LOG.error(sb);
return null;
}
int parentId = getParent(id);
if (parentId >= id) {
if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT);
}
if (visited != null) visited.add(id);
VirtualFileSystemEntry result;
if (parentId == 0) {
myRootsLock.readLock().lock();
try {
result = myRootsById.get(id);
}
finally {
myRootsLock.readLock().unlock();
}
}
else {
VirtualFileSystemEntry parentFile = findFileById(parentId, cachedOnly, visited, mask | id);
if (parentFile instanceof VirtualDirectoryImpl) {
result = ((VirtualDirectoryImpl)parentFile).findChildById(id, cachedOnly);
}
else {
result = null;
}
}
if (result != null && result.isDirectory()) {
VirtualFileSystemEntry old = myIdToDirCache.put(id, result);
if (old != null) result = old;
}
return result;
}
@Override
@NotNull
public VirtualFile[] getRoots() {
myRootsLock.readLock().lock();
try {
Collection<VirtualFileSystemEntry> roots = myRoots.values();
return VfsUtilCore.toVirtualFileArray(roots);
}
finally {
myRootsLock.readLock().unlock();
}
}
@Override
@NotNull
public VirtualFile[] getRoots(@NotNull final NewVirtualFileSystem fs) {
final List<VirtualFile> roots = new ArrayList<VirtualFile>();
myRootsLock.readLock().lock();
try {
for (NewVirtualFile root : myRoots.values()) {
if (root.getFileSystem() == fs) {
roots.add(root);
}
}
}
finally {
myRootsLock.readLock().unlock();
}
return VfsUtilCore.toVirtualFileArray(roots);
}
@Override
@NotNull
public VirtualFile[] getLocalRoots() {
List<VirtualFile> roots = ContainerUtil.newSmartList();
myRootsLock.readLock().lock();
try {
for (NewVirtualFile root : myRoots.values()) {
if (root.isInLocalFileSystem() && !(root.getFileSystem() instanceof TempFileSystem)) {
roots.add(root);
}
}
}
finally {
myRootsLock.readLock().unlock();
}
return VfsUtilCore.toVirtualFileArray(roots);
}
private VirtualFileSystemEntry applyEvent(@NotNull VFileEvent event) {
try {
if (event instanceof VFileCreateEvent) {
final VFileCreateEvent createEvent = (VFileCreateEvent)event;
return executeCreateChild(createEvent.getParent(), createEvent.getChildName());
}
else if (event instanceof VFileDeleteEvent) {
final VFileDeleteEvent deleteEvent = (VFileDeleteEvent)event;
executeDelete(deleteEvent.getFile());
}
else if (event instanceof VFileContentChangeEvent) {
final VFileContentChangeEvent contentUpdateEvent = (VFileContentChangeEvent)event;
executeTouch(contentUpdateEvent.getFile(), contentUpdateEvent.isFromRefresh(), contentUpdateEvent.getModificationStamp());
}
else if (event instanceof VFileCopyEvent) {
final VFileCopyEvent copyEvent = (VFileCopyEvent)event;
return executeCreateChild(copyEvent.getNewParent(), copyEvent.getNewChildName());
}
else if (event instanceof VFileMoveEvent) {
final VFileMoveEvent moveEvent = (VFileMoveEvent)event;
executeMove(moveEvent.getFile(), moveEvent.getNewParent());
}
else if (event instanceof VFilePropertyChangeEvent) {
final VFilePropertyChangeEvent propertyChangeEvent = (VFilePropertyChangeEvent)event;
if (VirtualFile.PROP_NAME.equals(propertyChangeEvent.getPropertyName())) {
executeRename(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue());
}
else if (VirtualFile.PROP_WRITABLE.equals(propertyChangeEvent.getPropertyName())) {
executeSetWritable(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue());
}
else if (VirtualFile.PROP_HIDDEN.equals(propertyChangeEvent.getPropertyName())) {
executeSetHidden(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue());
}
else if (VirtualFile.PROP_SYMLINK_TARGET.equals(propertyChangeEvent.getPropertyName())) {
executeSetTarget(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue());
}
}
}
catch (Exception e) {
// Exception applying single event should not prevent other events from applying.
LOG.error(e);
}
return null;
}
@NotNull
@NonNls
public String toString() {
return "PersistentFS";
}
private static VirtualFileSystemEntry executeCreateChild(@NotNull VirtualFile parent, @NotNull String name) {
final NewVirtualFileSystem delegate = getDelegate(parent);
final VirtualFile fake = new FakeVirtualFile(parent, name);
final FileAttributes attributes = delegate.getAttributes(fake);
if (attributes != null) {
final int parentId = getFileId(parent);
final int childId = createAndFillRecord(delegate, fake, parentId, attributes);
appendIdToParentList(parentId, childId);
assert parent instanceof VirtualDirectoryImpl : parent;
final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent;
VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem());
dir.addChild(child);
return child;
}
return null;
}
private static int createAndFillRecord(@NotNull NewVirtualFileSystem delegateSystem,
@NotNull VirtualFile delegateFile,
int parentId,
@NotNull FileAttributes attributes) {
final int childId = FSRecords.createRecord();
writeAttributesToRecord(childId, parentId, delegateFile, delegateSystem, attributes);
return childId;
}
private static void appendIdToParentList(final int parentId, final int childId) {
int[] childrenList = FSRecords.list(parentId);
childrenList = ArrayUtil.append(childrenList, childId);
FSRecords.updateList(parentId, childrenList);
}
private void executeDelete(@NotNull VirtualFile file) {
if (!file.exists()) {
LOG.error("Deleting a file, which does not exist: " + file.getPath());
return;
}
clearIdCache();
int id = getFileId(file);
final VirtualFile parent = file.getParent();
final int parentId = parent == null ? 0 : getFileId(parent);
if (parentId == 0) {
String rootUrl = normalizeRootUrl(file.getPath(), (NewVirtualFileSystem)file.getFileSystem());
myRootsLock.writeLock().lock();
try {
myRoots.remove(rootUrl);
myRootsById.remove(id);
FSRecords.deleteRootRecord(id);
}
finally {
myRootsLock.writeLock().unlock();
}
}
else {
removeIdFromParentList(parentId, id, parent, file);
VirtualDirectoryImpl directory = (VirtualDirectoryImpl)file.getParent();
assert directory != null : file;
directory.removeChild(file);
}
FSRecords.deleteRecordRecursively(id);
invalidateSubtree(file);
}
private static void invalidateSubtree(@NotNull VirtualFile file) {
final VirtualFileSystemEntry impl = (VirtualFileSystemEntry)file;
impl.invalidate();
for (VirtualFile child : impl.getCachedChildren()) {
invalidateSubtree(child);
}
}
private static void removeIdFromParentList(final int parentId, final int id, @NotNull VirtualFile parent, VirtualFile file) {
int[] childList = FSRecords.list(parentId);
int index = ArrayUtil.indexOf(childList, id);
if (index == -1) {
throw new RuntimeException("Cannot find child (" + id + ")" + file
+ "\n\tin (" + parentId + ")" + parent
+ "\n\tactual children:" + Arrays.toString(childList));
}
childList = ArrayUtil.remove(childList, index);
FSRecords.updateList(parentId, childList);
}
private static void executeRename(@NotNull VirtualFile file, @NotNull final String newName) {
final int id = getFileId(file);
FSRecords.setName(id, newName);
((VirtualFileSystemEntry)file).setNewName(newName);
}
private static void executeSetWritable(@NotNull VirtualFile file, boolean writableFlag) {
setFlag(file, IS_READ_ONLY, !writableFlag);
((VirtualFileSystemEntry)file).updateProperty(VirtualFile.PROP_WRITABLE, writableFlag);
}
private static void executeSetHidden(@NotNull VirtualFile file, boolean hiddenFlag) {
setFlag(file, IS_HIDDEN, hiddenFlag);
((VirtualFileSystemEntry)file).updateProperty(VirtualFile.PROP_HIDDEN, hiddenFlag);
}
private static void executeSetTarget(@NotNull VirtualFile file, String target) {
((VirtualFileSystemEntry)file).setLinkTarget(target);
}
private static void setFlag(@NotNull VirtualFile file, int mask, boolean value) {
setFlag(getFileId(file), mask, value);
}
private static void setFlag(final int id, final int mask, final boolean value) {
int oldFlags = FSRecords.getFlags(id);
int flags = value ? oldFlags | mask : oldFlags & ~mask;
if (oldFlags != flags) {
FSRecords.setFlags(id, flags, true);
}
}
private static boolean checkFlag(int fileId, int mask) {
return (FSRecords.getFlags(fileId) & mask) != 0;
}
private static void executeTouch(@NotNull VirtualFile file, boolean reloadContentFromDelegate, long newModificationStamp) {
if (reloadContentFromDelegate) {
setFlag(file, MUST_RELOAD_CONTENT, true);
}
final NewVirtualFileSystem delegate = getDelegate(file);
final FileAttributes attributes = delegate.getAttributes(file);
FSRecords.setLength(getFileId(file), attributes != null ? attributes.length : DEFAULT_LENGTH);
FSRecords.setTimestamp(getFileId(file), attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP);
((VirtualFileSystemEntry)file).setModificationStamp(newModificationStamp);
}
private void executeMove(@NotNull VirtualFile file, @NotNull VirtualFile newParent) {
clearIdCache();
final int fileId = getFileId(file);
final int newParentId = getFileId(newParent);
final int oldParentId = getFileId(file.getParent());
removeIdFromParentList(oldParentId, fileId, file.getParent(), file);
FSRecords.setParent(fileId, newParentId);
appendIdToParentList(newParentId, fileId);
((VirtualFileSystemEntry)file).setParent(newParent);
}
@Override
public String getName(int id) {
assert id > 0;
return FSRecords.getName(id);
}
@TestOnly
public void cleanPersistedContents() {
final int[] roots = FSRecords.listRoots();
for (int root : roots) {
cleanPersistedContentsRecursively(root);
}
}
@TestOnly
private void cleanPersistedContentsRecursively(int id) {
if (isDirectory(getFileAttributes(id))) {
for (int child : FSRecords.list(id)) {
cleanPersistedContentsRecursively(child);
}
}
else {
setFlag(id, MUST_RELOAD_CONTENT, true);
}
}
private abstract static class AbstractRoot extends VirtualDirectoryImpl {
public AbstractRoot(int id, VfsData.Segment segment, VfsData.DirectoryData data, NewVirtualFileSystem fs) {
super(id, segment, data, null, fs);
}
@NotNull
@Override
public abstract CharSequence getNameSequence();
@Override
protected abstract char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef);
@Override
public void setNewName(@NotNull String newName) {
throw new IncorrectOperationException();
}
@Override
public final void setParent(@NotNull VirtualFile newParent) {
throw new IncorrectOperationException();
}
}
private static class JarRoot extends AbstractRoot {
private final VirtualFile myParentLocalFile;
private final String myParentPath;
private JarRoot(@NotNull NewVirtualFileSystem fs, int id, VfsData.Segment segment, VfsData.DirectoryData data, VirtualFile parentLocalFile) {
super(id, segment, data, fs);
myParentLocalFile = parentLocalFile;
myParentPath = myParentLocalFile.getPath();
}
@NotNull
@Override
public CharSequence getNameSequence() {
return myParentLocalFile.getNameSequence();
}
@Override
protected char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef) {
char[] chars = new char[myParentPath.length() + JarFileSystem.JAR_SEPARATOR.length() + accumulatedPathLength];
positionRef[0] = copyString(chars, positionRef[0], myParentPath);
positionRef[0] = copyString(chars, positionRef[0], JarFileSystem.JAR_SEPARATOR);
return chars;
}
}
private static class FsRoot extends AbstractRoot {
private final String myName;
private FsRoot(@NotNull NewVirtualFileSystem fs, int id, VfsData.Segment segment, VfsData.DirectoryData data, @NotNull String basePath) {
super(id, segment, data, fs);
myName = FileUtil.toSystemIndependentName(basePath);
}
@NotNull
@Override
public CharSequence getNameSequence() {
return myName;
}
@Override
protected char[] appendPathOnFileSystem(int pathLength, int[] position) {
String name = getName();
int nameLength = name.length();
int rootPathLength = pathLength + nameLength;
// otherwise we called this as a part of longer file path calculation and slash will be added anyway
boolean appendSlash = SystemInfo.isWindows && nameLength == 2 && name.charAt(1) == ':' && pathLength == 0;
if (appendSlash) ++rootPathLength;
char[] chars = new char[rootPathLength];
position[0] = copyString(chars, position[0], name);
if (appendSlash) {
chars[position[0]++] = '/';
}
return chars;
}
}
}
| platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.newvfs.persistent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.util.LowMemoryWatcher;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.*;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.openapi.vfs.newvfs.*;
import com.intellij.openapi.vfs.newvfs.events.*;
import com.intellij.openapi.vfs.newvfs.impl.*;
import com.intellij.util.*;
import com.intellij.util.containers.ConcurrentIntObjectMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.EmptyIntHashSet;
import com.intellij.util.io.ReplicatorInputStream;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import gnu.trove.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author max
*/
public class PersistentFSImpl extends PersistentFS implements ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.persistent.PersistentFS");
private final MessageBus myEventBus;
private final ReadWriteLock myRootsLock = new ReentrantReadWriteLock();
private final Map<String, VirtualFileSystemEntry> myRoots = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
private final TIntObjectHashMap<VirtualFileSystemEntry> myRootsById = new TIntObjectHashMap<VirtualFileSystemEntry>();
private final ConcurrentIntObjectMap<VirtualFileSystemEntry> myIdToDirCache = ContainerUtil.createConcurrentIntObjectMap();
private final Object myInputLock = new Object();
private final AtomicBoolean myShutDown = new AtomicBoolean(false);
@SuppressWarnings("FieldCanBeLocal")
private final LowMemoryWatcher myWatcher = LowMemoryWatcher.register(new Runnable() {
@Override
public void run() {
clearIdCache();
}
});
public PersistentFSImpl(@NotNull MessageBus bus) {
myEventBus = bus;
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override
public void run() {
performShutdown();
}
});
}
@Override
public void initComponent() {
FSRecords.connect();
}
@Override
public void disposeComponent() {
performShutdown();
}
private void performShutdown() {
if (myShutDown.compareAndSet(false, true)) {
LOG.info("VFS dispose started");
FSRecords.dispose();
LOG.info("VFS dispose completed");
}
}
@Override
@NonNls
@NotNull
public String getComponentName() {
return "app.component.PersistentFS";
}
@Override
public boolean areChildrenLoaded(@NotNull final VirtualFile dir) {
return areChildrenLoaded(getFileId(dir));
}
@Override
public long getCreationTimestamp() {
return FSRecords.getCreationTimestamp();
}
@NotNull
private static NewVirtualFileSystem getDelegate(@NotNull VirtualFile file) {
return (NewVirtualFileSystem)file.getFileSystem();
}
@Override
public boolean wereChildrenAccessed(@NotNull final VirtualFile dir) {
return FSRecords.wereChildrenAccessed(getFileId(dir));
}
@Override
@NotNull
public String[] list(@NotNull final VirtualFile file) {
int id = getFileId(file);
FSRecords.NameId[] nameIds = FSRecords.listAll(id);
if (!areChildrenLoaded(id)) {
nameIds = persistAllChildren(file, id, nameIds);
}
return ContainerUtil.map2Array(nameIds, String.class, new Function<FSRecords.NameId, String>() {
@Override
public String fun(FSRecords.NameId id) {
return id.name.toString();
}
});
}
@Override
@NotNull
public String[] listPersisted(@NotNull VirtualFile parent) {
return listPersisted(FSRecords.list(getFileId(parent)));
}
@NotNull
private static String[] listPersisted(@NotNull int[] childrenIds) {
String[] names = ArrayUtil.newStringArray(childrenIds.length);
for (int i = 0; i < childrenIds.length; i++) {
names[i] = FSRecords.getName(childrenIds[i]);
}
return names;
}
@NotNull
private static FSRecords.NameId[] persistAllChildren(@NotNull final VirtualFile file, final int id, @NotNull FSRecords.NameId[] current) {
final NewVirtualFileSystem fs = replaceWithNativeFS(getDelegate(file));
String[] delegateNames = VfsUtil.filterNames(fs.list(file));
if (delegateNames.length == 0 && current.length > 0) {
return current;
}
Set<String> toAdd = ContainerUtil.newHashSet(delegateNames);
for (FSRecords.NameId nameId : current) {
toAdd.remove(nameId.name.toString());
}
final TIntArrayList childrenIds = new TIntArrayList(current.length + toAdd.size());
final List<FSRecords.NameId> nameIds = ContainerUtil.newArrayListWithCapacity(current.length + toAdd.size());
for (FSRecords.NameId nameId : current) {
childrenIds.add(nameId.id);
nameIds.add(nameId);
}
for (String newName : toAdd) {
FakeVirtualFile child = new FakeVirtualFile(file, newName);
FileAttributes attributes = fs.getAttributes(child);
if (attributes != null) {
int childId = createAndFillRecord(fs, child, id, attributes);
childrenIds.add(childId);
nameIds.add(new FSRecords.NameId(childId, FileNameCache.storeName(newName), newName));
}
}
FSRecords.updateList(id, childrenIds.toNativeArray());
setChildrenCached(id);
return nameIds.toArray(new FSRecords.NameId[nameIds.size()]);
}
public static void setChildrenCached(int id) {
int flags = FSRecords.getFlags(id);
FSRecords.setFlags(id, flags | CHILDREN_CACHED_FLAG, true);
}
@Override
@NotNull
public FSRecords.NameId[] listAll(@NotNull VirtualFile parent) {
final int parentId = getFileId(parent);
FSRecords.NameId[] nameIds = FSRecords.listAll(parentId);
if (!areChildrenLoaded(parentId)) {
return persistAllChildren(parent, parentId, nameIds);
}
return nameIds;
}
private static boolean areChildrenLoaded(final int parentId) {
return (FSRecords.getFlags(parentId) & CHILDREN_CACHED_FLAG) != 0;
}
@Override
@Nullable
public DataInputStream readAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) {
return FSRecords.readAttributeWithLock(getFileId(file), att);
}
@Override
@NotNull
public DataOutputStream writeAttribute(@NotNull final VirtualFile file, @NotNull final FileAttribute att) {
return FSRecords.writeAttribute(getFileId(file), att);
}
@Nullable
private static DataInputStream readContent(@NotNull VirtualFile file) {
return FSRecords.readContent(getFileId(file));
}
@Nullable
private static DataInputStream readContentById(int contentId) {
return FSRecords.readContentById(contentId);
}
@NotNull
private static DataOutputStream writeContent(@NotNull VirtualFile file, boolean readOnly) {
return FSRecords.writeContent(getFileId(file), readOnly);
}
private static void writeContent(@NotNull VirtualFile file, ByteSequence content, boolean readOnly) throws IOException {
FSRecords.writeContent(getFileId(file), content, readOnly);
}
@Override
public int storeUnlinkedContent(@NotNull byte[] bytes) {
return FSRecords.storeUnlinkedContent(bytes);
}
@Override
public int getModificationCount(@NotNull final VirtualFile file) {
return FSRecords.getModCount(getFileId(file));
}
@Override
public int getCheapFileSystemModificationCount() {
return FSRecords.getLocalModCount();
}
@Override
public int getFilesystemModificationCount() {
return FSRecords.getModCount();
}
private static boolean writeAttributesToRecord(final int id,
final int parentId,
@NotNull VirtualFile file,
@NotNull NewVirtualFileSystem fs,
@NotNull FileAttributes attributes) {
String name = file.getName();
if (!name.isEmpty()) {
if (namesEqual(fs, name, FSRecords.getName(id))) return false; // TODO: Handle root attributes change.
}
else {
if (areChildrenLoaded(id)) return false; // TODO: hack
}
FSRecords.writeAttributesToRecord(id, parentId, attributes, name);
return true;
}
@Override
public int getFileAttributes(int id) {
assert id > 0;
//noinspection MagicConstant
return FSRecords.getFlags(id);
}
@Override
public boolean isDirectory(@NotNull final VirtualFile file) {
return isDirectory(getFileAttributes(getFileId(file)));
}
private static int getParent(final int id) {
assert id > 0;
return FSRecords.getParent(id);
}
private static boolean namesEqual(@NotNull VirtualFileSystem fs, @NotNull String n1, String n2) {
return fs.isCaseSensitive() ? n1.equals(n2) : n1.equalsIgnoreCase(n2);
}
@Override
public boolean exists(@NotNull final VirtualFile fileOrDirectory) {
return ((VirtualFileWithId)fileOrDirectory).getId() > 0;
}
@Override
public long getTimeStamp(@NotNull final VirtualFile file) {
return FSRecords.getTimestamp(getFileId(file));
}
@Override
public void setTimeStamp(@NotNull final VirtualFile file, final long modStamp) throws IOException {
final int id = getFileId(file);
FSRecords.setTimestamp(id, modStamp);
getDelegate(file).setTimeStamp(file, modStamp);
}
private static int getFileId(@NotNull VirtualFile file) {
final int id = ((VirtualFileWithId)file).getId();
if (id <= 0) {
throw new InvalidVirtualFileAccessException(file);
}
return id;
}
@Override
public boolean isSymLink(@NotNull VirtualFile file) {
return isSymLink(getFileAttributes(getFileId(file)));
}
@Override
public String resolveSymLink(@NotNull VirtualFile file) {
throw new UnsupportedOperationException();
}
@Override
public boolean isSpecialFile(@NotNull VirtualFile file) {
return isSpecialFile(getFileAttributes(getFileId(file)));
}
@Override
public boolean isWritable(@NotNull VirtualFile file) {
return (getFileAttributes(getFileId(file)) & IS_READ_ONLY) == 0;
}
@Override
public boolean isHidden(@NotNull VirtualFile file) {
return (getFileAttributes(getFileId(file)) & IS_HIDDEN) != 0;
}
@Override
public void setWritable(@NotNull final VirtualFile file, final boolean writableFlag) throws IOException {
getDelegate(file).setWritable(file, writableFlag);
boolean oldWritable = isWritable(file);
if (oldWritable != writableFlag) {
processEvent(new VFilePropertyChangeEvent(this, file, VirtualFile.PROP_WRITABLE, oldWritable, writableFlag, false));
}
}
@Override
public int getId(@NotNull VirtualFile parent, @NotNull String childName, @NotNull NewVirtualFileSystem fs) {
int parentId = getFileId(parent);
int[] children = FSRecords.list(parentId);
if (children.length > 0) {
// fast path, check that some child has same nameId as given name, this avoid O(N) on retrieving names for processing non-cached children
int nameId = FSRecords.getNameId(childName);
for (final int childId : children) {
if (nameId == FSRecords.getNameId(childId)) {
return childId;
}
}
// for case sensitive system the above check is exhaustive in consistent state of vfs
}
for (final int childId : children) {
if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId;
}
final VirtualFile fake = new FakeVirtualFile(parent, childName);
final FileAttributes attributes = fs.getAttributes(fake);
if (attributes != null) {
final int child = createAndFillRecord(fs, fake, parentId, attributes);
FSRecords.updateList(parentId, ArrayUtil.append(children, child));
return child;
}
return 0;
}
@Override
public long getLength(@NotNull final VirtualFile file) {
long len;
if (mustReloadContent(file)) {
len = reloadLengthFromDelegate(file, getDelegate(file));
}
else {
final int id = getFileId(file);
len = FSRecords.getLength(id);
}
return len;
}
@NotNull
@Override
public VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile parent, @NotNull String name) throws IOException {
getDelegate(file).copyFile(requestor, file, parent, name);
processEvent(new VFileCopyEvent(requestor, file, parent, name));
final VirtualFile child = parent.findChild(name);
if (child == null) {
throw new IOException("Cannot create child");
}
return child;
}
@NotNull
@Override
public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException {
getDelegate(parent).createChildDirectory(requestor, parent, dir);
processEvent(new VFileCreateEvent(requestor, parent, dir, true, false));
final VirtualFile child = parent.findChild(dir);
if (child == null) {
throw new IOException("Cannot create child directory '" + dir + "' at " + parent.getPath());
}
return child;
}
@NotNull
@Override
public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
getDelegate(parent).createChildFile(requestor, parent, file);
processEvent(new VFileCreateEvent(requestor, parent, file, false, false));
final VirtualFile child = parent.findChild(file);
if (child == null) {
throw new IOException("Cannot create child file '" + file + "' at " + parent.getPath());
}
return child;
}
@Override
public void deleteFile(final Object requestor, @NotNull final VirtualFile file) throws IOException {
final NewVirtualFileSystem delegate = getDelegate(file);
delegate.deleteFile(requestor, file);
if (!delegate.exists(file)) {
processEvent(new VFileDeleteEvent(requestor, file, false));
}
}
@Override
public void renameFile(final Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException {
getDelegate(file).renameFile(requestor, file, newName);
String oldName = file.getName();
if (!newName.equals(oldName)) {
processEvent(new VFilePropertyChangeEvent(requestor, file, VirtualFile.PROP_NAME, oldName, newName, false));
}
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {
return contentsToByteArray(file, true);
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file, boolean cacheContent) throws IOException {
InputStream contentStream = null;
boolean reloadFromDelegate;
boolean outdated;
int fileId;
synchronized (myInputLock) {
fileId = getFileId(file);
outdated = checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L;
reloadFromDelegate = outdated || (contentStream = readContent(file)) == null;
}
if (reloadFromDelegate) {
final NewVirtualFileSystem delegate = getDelegate(file);
final byte[] content;
if (outdated) {
// in this case, file can have out-of-date length. so, update it first (it's needed for correct contentsToByteArray() work)
// see IDEA-90813 for possible bugs
FSRecords.setLength(fileId, delegate.getLength(file));
content = delegate.contentsToByteArray(file);
}
else {
// a bit of optimization
content = delegate.contentsToByteArray(file);
FSRecords.setLength(fileId, content.length);
}
ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
// we should cache every local files content
// because the local history feature is currently depends on this cache,
// perforce offline mode as well
if ((!delegate.isReadOnly() ||
// do not cache archive content unless asked
cacheContent && !application.isInternal() && !application.isUnitTestMode()) &&
content.length <= PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) {
synchronized (myInputLock) {
writeContent(file, new ByteSequence(content), delegate.isReadOnly());
setFlag(file, MUST_RELOAD_CONTENT, false);
}
}
return content;
}
else {
try {
final int length = (int)file.getLength();
assert length >= 0 : file;
return FileUtil.loadBytes(contentStream, length);
}
catch (IOException e) {
throw FSRecords.handleError(e);
}
}
}
@Override
@NotNull
public byte[] contentsToByteArray(int contentId) throws IOException {
final DataInputStream stream = readContentById(contentId);
assert stream != null : contentId;
return FileUtil.loadBytes(stream);
}
@Override
@NotNull
public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {
synchronized (myInputLock) {
InputStream contentStream;
if (mustReloadContent(file) || (contentStream = readContent(file)) == null) {
NewVirtualFileSystem delegate = getDelegate(file);
long len = reloadLengthFromDelegate(file, delegate);
InputStream nativeStream = delegate.getInputStream(file);
if (len > PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) return nativeStream;
return createReplicator(file, nativeStream, len, delegate.isReadOnly());
}
else {
return contentStream;
}
}
}
private static long reloadLengthFromDelegate(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem delegate) {
final long len = delegate.getLength(file);
FSRecords.setLength(getFileId(file), len);
return len;
}
private InputStream createReplicator(@NotNull final VirtualFile file,
final InputStream nativeStream,
final long fileLength,
final boolean readOnly) throws IOException {
if (nativeStream instanceof BufferExposingByteArrayInputStream) {
// optimization
BufferExposingByteArrayInputStream byteStream = (BufferExposingByteArrayInputStream )nativeStream;
byte[] bytes = byteStream.getInternalBuffer();
storeContentToStorage(fileLength, file, readOnly, bytes, bytes.length);
return nativeStream;
}
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
final BufferExposingByteArrayOutputStream cache = new BufferExposingByteArrayOutputStream((int)fileLength);
return new ReplicatorInputStream(nativeStream, cache) {
@Override
public void close() throws IOException {
super.close();
storeContentToStorage(fileLength, file, readOnly, cache.getInternalBuffer(), cache.size());
}
};
}
private void storeContentToStorage(long fileLength,
@NotNull VirtualFile file,
boolean readOnly, @NotNull byte[] bytes, int bytesLength)
throws IOException {
synchronized (myInputLock) {
if (bytesLength == fileLength) {
writeContent(file, new ByteSequence(bytes, 0, bytesLength), readOnly);
setFlag(file, MUST_RELOAD_CONTENT, false);
}
else {
setFlag(file, MUST_RELOAD_CONTENT, true);
}
}
}
private static boolean mustReloadContent(@NotNull VirtualFile file) {
int fileId = getFileId(file);
return checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L;
}
@Override
@NotNull
public OutputStream getOutputStream(@NotNull final VirtualFile file,
final Object requestor,
final long modStamp,
final long timeStamp) throws IOException {
return new ByteArrayOutputStream() {
private boolean closed; // protection against user calling .close() twice
@Override
public void close() throws IOException {
if (closed) return;
super.close();
VFileContentChangeEvent event = new VFileContentChangeEvent(requestor, file, file.getModificationStamp(), modStamp, false);
List<VFileContentChangeEvent> events = Collections.singletonList(event);
BulkFileListener publisher = myEventBus.syncPublisher(VirtualFileManager.VFS_CHANGES);
publisher.before(events);
NewVirtualFileSystem delegate = getDelegate(file);
OutputStream ioFileStream = delegate.getOutputStream(file, requestor, modStamp, timeStamp);
// FSRecords.ContentOutputStream already buffered, no need to wrap in BufferedStream
OutputStream persistenceStream = writeContent(file, delegate.isReadOnly());
try {
persistenceStream.write(buf, 0, count);
}
finally {
try {
ioFileStream.write(buf, 0, count);
}
finally {
closed = true;
persistenceStream.close();
ioFileStream.close();
executeTouch(file, false, event.getModificationStamp());
publisher.after(events);
}
}
}
};
}
@Override
public int acquireContent(@NotNull VirtualFile file) {
return FSRecords.acquireFileContent(getFileId(file));
}
@Override
public void releaseContent(int contentId) {
FSRecords.releaseContent(contentId);
}
@Override
public int getCurrentContentId(@NotNull VirtualFile file) {
return FSRecords.getContentId(getFileId(file));
}
@Override
public void moveFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent) throws IOException {
getDelegate(file).moveFile(requestor, file, newParent);
processEvent(new VFileMoveEvent(requestor, file, newParent));
}
private void processEvent(@NotNull VFileEvent event) {
processEvents(Collections.singletonList(event));
}
private static class EventWrapper {
private final VFileDeleteEvent event;
private final int id;
private EventWrapper(final VFileDeleteEvent event, final int id) {
this.event = event;
this.id = id;
}
}
@NotNull private static final Comparator<EventWrapper> DEPTH_COMPARATOR = new Comparator<EventWrapper>() {
@Override
public int compare(@NotNull final EventWrapper o1, @NotNull final EventWrapper o2) {
return o1.event.getFileDepth() - o2.event.getFileDepth();
}
};
@NotNull
private static List<VFileEvent> validateEvents(@NotNull List<VFileEvent> events) {
final List<EventWrapper> deletionEvents = ContainerUtil.newArrayList();
for (int i = 0, size = events.size(); i < size; i++) {
final VFileEvent event = events.get(i);
if (event instanceof VFileDeleteEvent && event.isValid()) {
deletionEvents.add(new EventWrapper((VFileDeleteEvent)event, i));
}
}
final TIntHashSet invalidIDs;
if (deletionEvents.isEmpty()) {
invalidIDs = EmptyIntHashSet.INSTANCE;
}
else {
ContainerUtil.quickSort(deletionEvents, DEPTH_COMPARATOR);
invalidIDs = new TIntHashSet(deletionEvents.size());
final Set<VirtualFile> dirsToBeDeleted = new THashSet<VirtualFile>(deletionEvents.size());
nextEvent:
for (EventWrapper wrapper : deletionEvents) {
final VirtualFile candidate = wrapper.event.getFile();
VirtualFile parent = candidate;
while (parent != null) {
if (dirsToBeDeleted.contains(parent)) {
invalidIDs.add(wrapper.id);
continue nextEvent;
}
parent = parent.getParent();
}
if (candidate.isDirectory()) {
dirsToBeDeleted.add(candidate);
}
}
}
final List<VFileEvent> filtered = new ArrayList<VFileEvent>(events.size() - invalidIDs.size());
for (int i = 0, size = events.size(); i < size; i++) {
final VFileEvent event = events.get(i);
if (event.isValid() && !(event instanceof VFileDeleteEvent && invalidIDs.contains(i))) {
filtered.add(event);
}
}
return filtered;
}
@Override
public void processEvents(@NotNull List<VFileEvent> events) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
List<VFileEvent> validated = validateEvents(events);
BulkFileListener publisher = myEventBus.syncPublisher(VirtualFileManager.VFS_CHANGES);
publisher.before(validated);
THashMap<VirtualFile, List<VFileEvent>> parentToChildrenEventsChanges = null;
for (VFileEvent event : validated) {
VirtualFile changedParent = null;
if (event instanceof VFileCreateEvent) {
changedParent = ((VFileCreateEvent)event).getParent();
((VFileCreateEvent)event).resetCache();
}
else if (event instanceof VFileDeleteEvent) {
changedParent = ((VFileDeleteEvent)event).getFile().getParent();
}
if (changedParent != null) {
if (parentToChildrenEventsChanges == null) parentToChildrenEventsChanges = new THashMap<VirtualFile, List<VFileEvent>>();
List<VFileEvent> parentChildrenChanges = parentToChildrenEventsChanges.get(changedParent);
if (parentChildrenChanges == null) {
parentToChildrenEventsChanges.put(changedParent, parentChildrenChanges = new SmartList<VFileEvent>());
}
parentChildrenChanges.add(event);
}
else {
applyEvent(event);
}
}
if (parentToChildrenEventsChanges != null) {
parentToChildrenEventsChanges.forEachEntry(new TObjectObjectProcedure<VirtualFile, List<VFileEvent>>() {
@Override
public boolean execute(VirtualFile parent, List<VFileEvent> childrenEvents) {
applyChildrenChangeEvents(parent, childrenEvents);
return true;
}
});
parentToChildrenEventsChanges.clear();
}
publisher.after(validated);
}
private void applyChildrenChangeEvents(VirtualFile parent, List<VFileEvent> events) {
final NewVirtualFileSystem delegate = getDelegate(parent);
TIntArrayList childrenIdsUpdated = new TIntArrayList();
List<VirtualFile> childrenToBeUpdated = new SmartList<VirtualFile>();
final int parentId = getFileId(parent);
assert parentId != 0;
TIntHashSet parentChildrenIds = new TIntHashSet(FSRecords.list(parentId));
boolean hasRemovedChildren = false;
for (VFileEvent event : events) {
if (event instanceof VFileCreateEvent) {
String name = ((VFileCreateEvent)event).getChildName();
final VirtualFile fake = new FakeVirtualFile(parent, name);
final FileAttributes attributes = delegate.getAttributes(fake);
if (attributes != null) {
final int childId = createAndFillRecord(delegate, fake, parentId, attributes);
assert parent instanceof VirtualDirectoryImpl : parent;
final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent;
VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem());
childrenToBeUpdated.add(child);
childrenIdsUpdated.add(childId);
parentChildrenIds.add(childId);
}
}
else if (event instanceof VFileDeleteEvent) {
VirtualFile file = ((VFileDeleteEvent)event).getFile();
if (!file.exists()) {
LOG.error("Deleting a file, which does not exist: " + file.getPath());
continue;
}
hasRemovedChildren = true;
int id = getFileId(file);
childrenToBeUpdated.add(file);
childrenIdsUpdated.add(-id);
parentChildrenIds.remove(id);
}
}
FSRecords.updateList(parentId, parentChildrenIds.toArray());
if (hasRemovedChildren) clearIdCache();
VirtualDirectoryImpl parentImpl = (VirtualDirectoryImpl)parent;
for (int i = 0, len = childrenIdsUpdated.size(); i < len; ++i) {
final int childId = childrenIdsUpdated.get(i);
final VirtualFile childFile = childrenToBeUpdated.get(i);
if (childId > 0) {
parentImpl.addChild((VirtualFileSystemEntry)childFile);
}
else {
FSRecords.deleteRecordRecursively(-childId);
parentImpl.removeChild(childFile);
invalidateSubtree(childFile);
}
}
}
@Override
@Nullable
public VirtualFileSystemEntry findRoot(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) {
if (basePath.isEmpty()) {
LOG.error("Invalid root, fs=" + fs);
return null;
}
String rootUrl = normalizeRootUrl(basePath, fs);
myRootsLock.readLock().lock();
try {
VirtualFileSystemEntry root = myRoots.get(rootUrl);
if (root != null) return root;
}
finally {
myRootsLock.readLock().unlock();
}
final VirtualFileSystemEntry newRoot;
int rootId = FSRecords.findRootRecord(rootUrl);
VfsData.Segment segment = VfsData.getSegment(rootId, true);
VfsData.DirectoryData directoryData = new VfsData.DirectoryData();
if (fs instanceof JarFileSystem) {
String parentPath = basePath.substring(0, basePath.indexOf(JarFileSystem.JAR_SEPARATOR));
VirtualFile parentFile = LocalFileSystem.getInstance().findFileByPath(parentPath);
if (parentFile == null) return null;
FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(parentFile.getName());
if (type != FileTypes.ARCHIVE) return null;
newRoot = new JarRoot(fs, rootId, segment, directoryData, parentFile);
}
else {
newRoot = new FsRoot(fs, rootId, segment, directoryData, basePath);
}
FileAttributes attributes = fs.getAttributes(new StubVirtualFile() {
@NotNull
@Override
public String getPath() {
return newRoot.getPath();
}
@Nullable
@Override
public VirtualFile getParent() {
return null;
}
});
if (attributes == null || !attributes.isDirectory()) {
return null;
}
boolean mark = false;
myRootsLock.writeLock().lock();
try {
VirtualFileSystemEntry root = myRoots.get(rootUrl);
if (root != null) return root;
VfsData.initFile(rootId, segment, -1, directoryData);
mark = writeAttributesToRecord(rootId, 0, newRoot, fs, attributes);
myRoots.put(rootUrl, newRoot);
myRootsById.put(rootId, newRoot);
}
finally {
myRootsLock.writeLock().unlock();
}
if (!mark && attributes.lastModified != FSRecords.getTimestamp(rootId)) {
newRoot.markDirtyRecursively();
}
LOG.assertTrue(rootId == newRoot.getId(), "root=" + newRoot + " expected=" + rootId + " actual=" + newRoot.getId());
return newRoot;
}
@NotNull
private static String normalizeRootUrl(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) {
// need to protect against relative path of the form "/x/../y"
return UriUtil.trimTrailingSlashes(
fs.getProtocol() + URLUtil.SCHEME_SEPARATOR + VfsImplUtil.normalize(fs, FileUtil.toCanonicalPath(basePath)));
}
@Override
public void clearIdCache() {
myIdToDirCache.clear();
}
private static final int DEPTH_LIMIT = 75;
@Override
@Nullable
public NewVirtualFile findFileById(final int id) {
return findFileById(id, false, null, 0);
}
@Override
public NewVirtualFile findFileByIdIfCached(final int id) {
return findFileById(id, true, null, 0);
}
@Nullable
private VirtualFileSystemEntry findFileById(int id, boolean cachedOnly, TIntArrayList visited, int mask) {
VirtualFileSystemEntry cached = myIdToDirCache.get(id);
if (cached != null) return cached;
if (visited != null && (visited.size() >= DEPTH_LIMIT || (mask & id) == id && visited.contains(id))) {
@NonNls String sb = "Dead loop detected in persistent FS (id=" + id + " cached-only=" + cachedOnly + "):";
for (int i = 0; i < visited.size(); i++) {
int _id = visited.get(i);
sb += "\n " + _id + " '" + getName(_id) + "' " +
String.format("%02x", getFileAttributes(_id)) + ' ' + myIdToDirCache.containsKey(_id);
}
LOG.error(sb);
return null;
}
int parentId = getParent(id);
if (parentId >= id) {
if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT);
}
if (visited != null) visited.add(id);
VirtualFileSystemEntry result;
if (parentId == 0) {
myRootsLock.readLock().lock();
try {
result = myRootsById.get(id);
}
finally {
myRootsLock.readLock().unlock();
}
}
else {
VirtualFileSystemEntry parentFile = findFileById(parentId, cachedOnly, visited, mask | id);
if (parentFile instanceof VirtualDirectoryImpl) {
result = ((VirtualDirectoryImpl)parentFile).findChildById(id, cachedOnly);
}
else {
result = null;
}
}
if (result != null && result.isDirectory()) {
VirtualFileSystemEntry old = myIdToDirCache.put(id, result);
if (old != null) result = old;
}
return result;
}
@Override
@NotNull
public VirtualFile[] getRoots() {
myRootsLock.readLock().lock();
try {
Collection<VirtualFileSystemEntry> roots = myRoots.values();
return VfsUtilCore.toVirtualFileArray(roots);
}
finally {
myRootsLock.readLock().unlock();
}
}
@Override
@NotNull
public VirtualFile[] getRoots(@NotNull final NewVirtualFileSystem fs) {
final List<VirtualFile> roots = new ArrayList<VirtualFile>();
myRootsLock.readLock().lock();
try {
for (NewVirtualFile root : myRoots.values()) {
if (root.getFileSystem() == fs) {
roots.add(root);
}
}
}
finally {
myRootsLock.readLock().unlock();
}
return VfsUtilCore.toVirtualFileArray(roots);
}
@Override
@NotNull
public VirtualFile[] getLocalRoots() {
List<VirtualFile> roots = ContainerUtil.newSmartList();
myRootsLock.readLock().lock();
try {
for (NewVirtualFile root : myRoots.values()) {
if (root.isInLocalFileSystem() && !(root.getFileSystem() instanceof TempFileSystem)) {
roots.add(root);
}
}
}
finally {
myRootsLock.readLock().unlock();
}
return VfsUtilCore.toVirtualFileArray(roots);
}
private VirtualFileSystemEntry applyEvent(@NotNull VFileEvent event) {
try {
if (event instanceof VFileCreateEvent) {
final VFileCreateEvent createEvent = (VFileCreateEvent)event;
return executeCreateChild(createEvent.getParent(), createEvent.getChildName());
}
else if (event instanceof VFileDeleteEvent) {
final VFileDeleteEvent deleteEvent = (VFileDeleteEvent)event;
executeDelete(deleteEvent.getFile());
}
else if (event instanceof VFileContentChangeEvent) {
final VFileContentChangeEvent contentUpdateEvent = (VFileContentChangeEvent)event;
executeTouch(contentUpdateEvent.getFile(), contentUpdateEvent.isFromRefresh(), contentUpdateEvent.getModificationStamp());
}
else if (event instanceof VFileCopyEvent) {
final VFileCopyEvent copyEvent = (VFileCopyEvent)event;
return executeCreateChild(copyEvent.getNewParent(), copyEvent.getNewChildName());
}
else if (event instanceof VFileMoveEvent) {
final VFileMoveEvent moveEvent = (VFileMoveEvent)event;
executeMove(moveEvent.getFile(), moveEvent.getNewParent());
}
else if (event instanceof VFilePropertyChangeEvent) {
final VFilePropertyChangeEvent propertyChangeEvent = (VFilePropertyChangeEvent)event;
if (VirtualFile.PROP_NAME.equals(propertyChangeEvent.getPropertyName())) {
executeRename(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue());
}
else if (VirtualFile.PROP_WRITABLE.equals(propertyChangeEvent.getPropertyName())) {
executeSetWritable(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue());
}
else if (VirtualFile.PROP_HIDDEN.equals(propertyChangeEvent.getPropertyName())) {
executeSetHidden(propertyChangeEvent.getFile(), ((Boolean)propertyChangeEvent.getNewValue()).booleanValue());
}
else if (VirtualFile.PROP_SYMLINK_TARGET.equals(propertyChangeEvent.getPropertyName())) {
executeSetTarget(propertyChangeEvent.getFile(), (String)propertyChangeEvent.getNewValue());
}
}
}
catch (Exception e) {
// Exception applying single event should not prevent other events from applying.
LOG.error(e);
}
return null;
}
@NotNull
@NonNls
public String toString() {
return "PersistentFS";
}
private static VirtualFileSystemEntry executeCreateChild(@NotNull VirtualFile parent, @NotNull String name) {
final NewVirtualFileSystem delegate = getDelegate(parent);
final VirtualFile fake = new FakeVirtualFile(parent, name);
final FileAttributes attributes = delegate.getAttributes(fake);
if (attributes != null) {
final int parentId = getFileId(parent);
final int childId = createAndFillRecord(delegate, fake, parentId, attributes);
appendIdToParentList(parentId, childId);
assert parent instanceof VirtualDirectoryImpl : parent;
final VirtualDirectoryImpl dir = (VirtualDirectoryImpl)parent;
VirtualFileSystemEntry child = dir.createChild(name, childId, dir.getFileSystem());
dir.addChild(child);
return child;
}
return null;
}
private static int createAndFillRecord(@NotNull NewVirtualFileSystem delegateSystem,
@NotNull VirtualFile delegateFile,
int parentId,
@NotNull FileAttributes attributes) {
final int childId = FSRecords.createRecord();
writeAttributesToRecord(childId, parentId, delegateFile, delegateSystem, attributes);
return childId;
}
private static void appendIdToParentList(final int parentId, final int childId) {
int[] childrenList = FSRecords.list(parentId);
childrenList = ArrayUtil.append(childrenList, childId);
FSRecords.updateList(parentId, childrenList);
}
private void executeDelete(@NotNull VirtualFile file) {
if (!file.exists()) {
LOG.error("Deleting a file, which does not exist: " + file.getPath());
return;
}
clearIdCache();
int id = getFileId(file);
final VirtualFile parent = file.getParent();
final int parentId = parent == null ? 0 : getFileId(parent);
if (parentId == 0) {
String rootUrl = normalizeRootUrl(file.getPath(), (NewVirtualFileSystem)file.getFileSystem());
myRootsLock.writeLock().lock();
try {
myRoots.remove(rootUrl);
myRootsById.remove(id);
FSRecords.deleteRootRecord(id);
}
finally {
myRootsLock.writeLock().unlock();
}
}
else {
removeIdFromParentList(parentId, id, parent, file);
VirtualDirectoryImpl directory = (VirtualDirectoryImpl)file.getParent();
assert directory != null : file;
directory.removeChild(file);
}
FSRecords.deleteRecordRecursively(id);
invalidateSubtree(file);
}
private static void invalidateSubtree(@NotNull VirtualFile file) {
final VirtualFileSystemEntry impl = (VirtualFileSystemEntry)file;
impl.invalidate();
for (VirtualFile child : impl.getCachedChildren()) {
invalidateSubtree(child);
}
}
private static void removeIdFromParentList(final int parentId, final int id, @NotNull VirtualFile parent, VirtualFile file) {
int[] childList = FSRecords.list(parentId);
int index = ArrayUtil.indexOf(childList, id);
if (index == -1) {
throw new RuntimeException("Cannot find child (" + id + ")" + file
+ "\n\tin (" + parentId + ")" + parent
+ "\n\tactual children:" + Arrays.toString(childList));
}
childList = ArrayUtil.remove(childList, index);
FSRecords.updateList(parentId, childList);
}
private static void executeRename(@NotNull VirtualFile file, @NotNull final String newName) {
final int id = getFileId(file);
FSRecords.setName(id, newName);
((VirtualFileSystemEntry)file).setNewName(newName);
}
private static void executeSetWritable(@NotNull VirtualFile file, boolean writableFlag) {
setFlag(file, IS_READ_ONLY, !writableFlag);
((VirtualFileSystemEntry)file).updateProperty(VirtualFile.PROP_WRITABLE, writableFlag);
}
private static void executeSetHidden(@NotNull VirtualFile file, boolean hiddenFlag) {
setFlag(file, IS_HIDDEN, hiddenFlag);
((VirtualFileSystemEntry)file).updateProperty(VirtualFile.PROP_HIDDEN, hiddenFlag);
}
private static void executeSetTarget(@NotNull VirtualFile file, String target) {
((VirtualFileSystemEntry)file).setLinkTarget(target);
}
private static void setFlag(@NotNull VirtualFile file, int mask, boolean value) {
setFlag(getFileId(file), mask, value);
}
private static void setFlag(final int id, final int mask, final boolean value) {
int oldFlags = FSRecords.getFlags(id);
int flags = value ? oldFlags | mask : oldFlags & ~mask;
if (oldFlags != flags) {
FSRecords.setFlags(id, flags, true);
}
}
private static boolean checkFlag(int fileId, int mask) {
return (FSRecords.getFlags(fileId) & mask) != 0;
}
private static void executeTouch(@NotNull VirtualFile file, boolean reloadContentFromDelegate, long newModificationStamp) {
if (reloadContentFromDelegate) {
setFlag(file, MUST_RELOAD_CONTENT, true);
}
final NewVirtualFileSystem delegate = getDelegate(file);
final FileAttributes attributes = delegate.getAttributes(file);
FSRecords.setLength(getFileId(file), attributes != null ? attributes.length : DEFAULT_LENGTH);
FSRecords.setTimestamp(getFileId(file), attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP);
((VirtualFileSystemEntry)file).setModificationStamp(newModificationStamp);
}
private void executeMove(@NotNull VirtualFile file, @NotNull VirtualFile newParent) {
clearIdCache();
final int fileId = getFileId(file);
final int newParentId = getFileId(newParent);
final int oldParentId = getFileId(file.getParent());
removeIdFromParentList(oldParentId, fileId, file.getParent(), file);
FSRecords.setParent(fileId, newParentId);
appendIdToParentList(newParentId, fileId);
((VirtualFileSystemEntry)file).setParent(newParent);
}
@Override
public String getName(int id) {
assert id > 0;
return FSRecords.getName(id);
}
@TestOnly
public void cleanPersistedContents() {
final int[] roots = FSRecords.listRoots();
for (int root : roots) {
cleanPersistedContentsRecursively(root);
}
}
@TestOnly
private void cleanPersistedContentsRecursively(int id) {
if (isDirectory(getFileAttributes(id))) {
for (int child : FSRecords.list(id)) {
cleanPersistedContentsRecursively(child);
}
}
else {
setFlag(id, MUST_RELOAD_CONTENT, true);
}
}
private abstract static class AbstractRoot extends VirtualDirectoryImpl {
public AbstractRoot(int id, VfsData.Segment segment, VfsData.DirectoryData data, NewVirtualFileSystem fs) {
super(id, segment, data, null, fs);
}
@NotNull
@Override
public abstract CharSequence getNameSequence();
@Override
protected abstract char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef);
@Override
public void setNewName(@NotNull String newName) {
throw new IncorrectOperationException();
}
@Override
public final void setParent(@NotNull VirtualFile newParent) {
throw new IncorrectOperationException();
}
}
private static class JarRoot extends AbstractRoot {
private final VirtualFile myParentLocalFile;
private final String myParentPath;
private JarRoot(@NotNull NewVirtualFileSystem fs, int id, VfsData.Segment segment, VfsData.DirectoryData data, VirtualFile parentLocalFile) {
super(id, segment, data, fs);
myParentLocalFile = parentLocalFile;
myParentPath = myParentLocalFile.getPath();
}
@NotNull
@Override
public CharSequence getNameSequence() {
return myParentLocalFile.getNameSequence();
}
@Override
protected char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef) {
char[] chars = new char[myParentPath.length() + JarFileSystem.JAR_SEPARATOR.length() + accumulatedPathLength];
positionRef[0] = copyString(chars, positionRef[0], myParentPath);
positionRef[0] = copyString(chars, positionRef[0], JarFileSystem.JAR_SEPARATOR);
return chars;
}
}
private static class FsRoot extends AbstractRoot {
private final String myName;
private FsRoot(@NotNull NewVirtualFileSystem fs, int id, VfsData.Segment segment, VfsData.DirectoryData data, @NotNull String basePath) {
super(id, segment, data, fs);
myName = FileUtil.toSystemIndependentName(basePath);
}
@NotNull
@Override
public CharSequence getNameSequence() {
return myName;
}
@Override
protected char[] appendPathOnFileSystem(int pathLength, int[] position) {
String name = getName();
int nameLength = name.length();
int rootPathLength = pathLength + nameLength;
// otherwise we called this as a part of longer file path calculation and slash will be added anyway
boolean appendSlash = SystemInfo.isWindows && nameLength == 2 && name.charAt(1) == ':' && pathLength == 0;
if (appendSlash) ++rootPathLength;
char[] chars = new char[rootPathLength];
position[0] = copyString(chars, position[0], name);
if (appendSlash) {
chars[position[0]++] = '/';
}
return chars;
}
}
}
| write virtual files in a write action
| platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java | write virtual files in a write action | <ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
<ide> if (closed) return;
<ide> super.close();
<ide>
<add> ApplicationManager.getApplication().assertWriteAccessAllowed();
<add>
<ide> VFileContentChangeEvent event = new VFileContentChangeEvent(requestor, file, file.getModificationStamp(), modStamp, false);
<ide> List<VFileContentChangeEvent> events = Collections.singletonList(event);
<ide> BulkFileListener publisher = myEventBus.syncPublisher(VirtualFileManager.VFS_CHANGES); |
|
Java | mit | e9d1653798d9a066de29305fe13ec430ddb71850 | 0 | jmigual/pKK,jmigual/pKK,jmigual/pKK | package presentacio;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import presentacio.Stats.StatsGlobalController;
import sun.applet.Main;
import java.awt.event.MouseEvent;
import java.io.IOException;
/**
* Created by Inigo on 04/12/2015.
*/
public class MainController extends AnchorPane {
@FXML
private StackPane leftArea;
private AnchorPane rootlayout;
private Stage shownStage;
private MainWindow main;
public MainController(MainWindow main){
this.main=main;
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainWindow.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
rootlayout = loader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public StackPane getLeftArea() {
return leftArea;
}
public AnchorPane getRootlayout() {
return rootlayout;
}
public void configureUser() {
shownStage = new Stage();
UserConfigController config = new UserConfigController(main);
shownStage.initModality(Modality.APPLICATION_MODAL);
shownStage.setScene(new Scene(config.getRootLayout()));
shownStage.sizeToScene();
shownStage.show();
}
public void showGlobal(){
FXMLLoader loader = new FXMLLoader(getClass().getResource("Stats/Stats_Global.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
leftArea.getChildren().clear();
leftArea.getChildren().add(loader.load());
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public void showPersonal(){
}
public void exit() {
Platform.exit();
}
public void trolla(){}
}
| Java/src/presentacio/MainController.java | package presentacio;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import presentacio.Stats.StatsGlobalController;
import sun.applet.Main;
import java.awt.event.MouseEvent;
import java.io.IOException;
/**
* Created by Inigo on 04/12/2015.
*/
public class MainController extends AnchorPane {
@FXML
private StackPane leftArea;
private AnchorPane rootlayout;
private Stage shownStage;
private MainWindow main;
public MainController(MainWindow main){
this.main=main;
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainWindow.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
rootlayout = loader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public StackPane getLeftArea() {
return leftArea;
}
public AnchorPane getRootlayout() {
return rootlayout;
}
public void configureUser() {
shownStage = new Stage();
UserConfigController config = new UserConfigController(main);
shownStage.initModality(Modality.APPLICATION_MODAL);
shownStage.setScene(new Scene(config.getRootLayout()));
shownStage.sizeToScene();
shownStage.show();
}
public void showGlobal(){
rootlayout = new StatsGlobalController(main);
}
public void showPersonal(){
}
public void exit() {
Platform.exit();
}
public void trolla(){}
}
| Intentant que els stats es carreguin a la finestra
| Java/src/presentacio/MainController.java | Intentant que els stats es carreguin a la finestra | <ide><path>ava/src/presentacio/MainController.java
<ide> }
<ide>
<ide> public void showGlobal(){
<del> rootlayout = new StatsGlobalController(main);
<add> FXMLLoader loader = new FXMLLoader(getClass().getResource("Stats/Stats_Global.fxml"));
<add> loader.setRoot(this);
<add> loader.setController(this);
<add> try {
<add> leftArea.getChildren().clear();
<add> leftArea.getChildren().add(loader.load());
<add> } catch (IOException exception) {
<add> throw new RuntimeException(exception);
<add> }
<ide> }
<ide>
<ide> public void showPersonal(){ |
|
JavaScript | apache-2.0 | b376e736190457976b219af8f4b9455ef3c1d0b4 | 0 | hasuniea/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,dilee/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,madhawap/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,charithag/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,DimalChandrasiri/carbon-device-mgt-plugins,GDLMadushanka/carbon-device-mgt-plugins,ruwany/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,Kamidu/carbon-device-mgt-plugins,wso2/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,harshanL/carbon-device-mgt-plugins,inoshperera/carbon-device-mgt-plugins,rasika/carbon-device-mgt-plugins,milanperera/carbon-device-mgt-plugins,lasanthaDLPDS/carbon-device-mgt-plugins,hasuniea/carbon-device-mgt-plugins | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Constants to define platform types available
var platformTypeConstants = {
"WINDOWS": "windows"
};
var responseCodes = {
"CREATED": "Created",
"SUCCESS": "201",
"INTERNAL_SERVER_ERROR": "Internal Server Error"
};
var configParams = {
"NOTIFIER_TYPE": "notifierType",
"NOTIFIER_FREQUENCY": "notifierFrequency",
"FCM_API_KEY": "fcmAPIKey",
"FCM_SENDER_ID": "fcmSenderId",
"ANDROID_EULA": "androidEula",
"IOS_EULA": "iosEula",
"CONFIG_COUNTRY": "configCountry",
"CONFIG_STATE": "configState",
"CONFIG_LOCALITY": "configLocality",
"CONFIG_ORGANIZATION": "configOrganization",
"CONFIG_ORGANIZATION_UNIT": "configOrganizationUnit",
"MDM_CERT_PASSWORD": "MDMCertPassword",
"MDM_CERT_TOPIC_ID": "MDMCertTopicID",
"APNS_CERT_PASSWORD": "APNSCertPassword",
"MDM_CERT": "MDMCert",
"MDM_CERT_NAME": "MDMCertName",
"APNS_CERT": "APNSCert",
"APNS_CERT_NAME": "APNSCertName",
"ORG_DISPLAY_NAME": "organizationDisplayName",
"GENERAL_EMAIL_HOST": "emailHost",
"GENERAL_EMAIL_PORT": "emailPort",
"GENERAL_EMAIL_USERNAME": "emailUsername",
"GENERAL_EMAIL_PASSWORD": "emailPassword",
"GENERAL_EMAIL_SENDER_ADDRESS": "emailSender",
"GENERAL_EMAIL_TEMPLATE": "emailTemplate",
"COMMON_NAME": "commonName",
"KEYSTORE_PASSWORD": "keystorePassword",
"PRIVATE_KEY_PASSWORD": "privateKeyPassword",
"BEFORE_EXPIRE": "beforeExpire",
"AFTER_EXPIRE": "afterExpire",
"WINDOWS_EULA": "windowsLicense",
"IOS_CONFIG_MDM_MODE": "iOSConfigMDMMode",
"IOS_CONFIG_APNS_MODE": "iOSConfigAPNSMode"
};
function promptErrorPolicyPlatform(errorMsg) {
var mainErrorMsgWrapper = "#platform-config-main-error-msg";
var mainErrorMsg = mainErrorMsgWrapper + " span";
$(mainErrorMsg).text(errorMsg);
$(mainErrorMsgWrapper).show();
}
$(document).ready(function () {
tinymce.init({
selector: "textarea",
height:500,
theme: "modern",
plugins: [
"autoresize",
"advlist autolink lists link image charmap print preview anchor",
"searchreplace visualblocks code fullscreen",
"insertdatetime image table contextmenu paste"
],
toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
});
var windowsConfigAPI = "/api/device-mgt/windows/v1.0/services/configuration";
invokerUtil.get(
windowsConfigAPI,
function (data) {
data = JSON.parse(data);
if (data != null && data.configuration != null) {
for (var i = 0; i < data.configuration.length; i++) {
var config = data.configuration[i];
if (config.name == configParams["NOTIFIER_FREQUENCY"]) {
$("input#windows-config-notifier-frequency").val(config.value / 1000);
} else if (config.name == configParams["WINDOWS_EULA"]) {
$("#windows-eula").val(config.value);
}
}
}
}, function (data) {
console.log(data);
}
);
$("select.select2[multiple=multiple]").select2({
tags: true
});
var errorMsgWrapperWindows = "#windows-config-error-msg";
var errorMsgWindows = "#windows-config-error-msg span";
var fileTypesWindows = ['jks'];
var notSupportedError = false;
var base64WindowsMDMCert = "";
var fileInputWindowsMDMCert = $('#windows-config-mdm-certificate');
var fileNameWindowsMDMCert = "";
var invalidFormatWindowsMDMCert = false;
$(fileInputWindowsMDMCert).change(function () {
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
$(errorMsgWindows).text("The File APIs are not fully supported in this browser.");
$(errorMsgWrapperWindows).removeClass("hidden");
notSupportedError = true;
return;
}
var file = fileInputWindowsMDMCert[0].files[0];
fileNameWindowsMDMCert = file.name;
var extension = file.name.split('.').pop().toLowerCase(),
isSuccess = fileTypesWindows.indexOf(extension) > -1;
if (isSuccess) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
base64WindowsMDMCert = event.target.result;
};
fileReader.readAsDataURL(file);
invalidFormatWindowsMDMCert = false;
} else {
base64MDMCert = "";
invalidFormatWindowsMDMCert = true;
}
});
$("button#save-windows-btn").click(function () {
var notifierFrequency = $("#windows-config-notifier-frequency").val();
var windowsLicense = tinyMCE.activeEditor.getContent();
if (!notifierFrequency) {
$(errorMsgWindows).text("Polling Interval is a required field. It cannot be empty.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else if (!windowsLicense) {
$(errorMsgWindows).text("License is a required field. It cannot be empty.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else if (!$.isNumeric(notifierFrequency)) {
$(errorMsgWindows).text("Provided Notifier frequency is invalid. It must be a number.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else {
var addConfigFormData = {};
var configList = new Array();
var paramNotifierFrequency = {
"name": configParams["NOTIFIER_FREQUENCY"],
"value": String(notifierFrequency * 1000),
"contentType": "text"
};
var windowsEula = {
"name": configParams["WINDOWS_EULA"],
"value": windowsLicense,
"contentType": "text"
};
configList.push(paramNotifierFrequency);
configList.push(windowsEula);
addConfigFormData.type = platformTypeConstants["WINDOWS"];
addConfigFormData.configuration = configList;
var addConfigAPI = windowsConfigAPI;
invokerUtil.put(
addConfigAPI,
addConfigFormData,
function (data, textStatus, jqXHR) {
data = jqXHR.status;
if (data == 200) {
$("#config-save-form").addClass("hidden");
$("#record-created-msg").removeClass("hidden");
} else if (data == 500) {
$(errorMsgWindows).text("Exception occurred at backend.");
} else if (data == 400) {
$(errorMsgWindows).text("Configurations cannot be empty.");
} else {
$(errorMsgWindows).text("An unexpected error occurred.");
}
$(errorMsgWrapperWindows).removeClass("hidden");
}, function (data) {
data = data.status;
if (data == 500) {
$(errorMsgWindows).text("Exception occurred at backend.");
} else if (data == 403) {
$(errorMsgWindows).text("Action was not permitted.");
} else {
$(errorMsgWindows).text("An unexpected error occurred.");
}
$(errorMsgWrapperWindows).removeClass("hidden");
}
);
}
});
}); | components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.windows.platform.configuration/public/js/platform-configuration.js | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Constants to define platform types available
var platformTypeConstants = {
"WINDOWS": "windows"
};
var responseCodes = {
"CREATED": "Created",
"SUCCESS": "201",
"INTERNAL_SERVER_ERROR": "Internal Server Error"
};
var configParams = {
"NOTIFIER_TYPE": "notifierType",
"NOTIFIER_FREQUENCY": "notifierFrequency",
"FCM_API_KEY": "fcmAPIKey",
"FCM_SENDER_ID": "fcmSenderId",
"ANDROID_EULA": "androidEula",
"IOS_EULA": "iosEula",
"CONFIG_COUNTRY": "configCountry",
"CONFIG_STATE": "configState",
"CONFIG_LOCALITY": "configLocality",
"CONFIG_ORGANIZATION": "configOrganization",
"CONFIG_ORGANIZATION_UNIT": "configOrganizationUnit",
"MDM_CERT_PASSWORD": "MDMCertPassword",
"MDM_CERT_TOPIC_ID": "MDMCertTopicID",
"APNS_CERT_PASSWORD": "APNSCertPassword",
"MDM_CERT": "MDMCert",
"MDM_CERT_NAME": "MDMCertName",
"APNS_CERT": "APNSCert",
"APNS_CERT_NAME": "APNSCertName",
"ORG_DISPLAY_NAME": "organizationDisplayName",
"GENERAL_EMAIL_HOST": "emailHost",
"GENERAL_EMAIL_PORT": "emailPort",
"GENERAL_EMAIL_USERNAME": "emailUsername",
"GENERAL_EMAIL_PASSWORD": "emailPassword",
"GENERAL_EMAIL_SENDER_ADDRESS": "emailSender",
"GENERAL_EMAIL_TEMPLATE": "emailTemplate",
"COMMON_NAME": "commonName",
"KEYSTORE_PASSWORD": "keystorePassword",
"PRIVATE_KEY_PASSWORD": "privateKeyPassword",
"BEFORE_EXPIRE": "beforeExpire",
"AFTER_EXPIRE": "afterExpire",
"WINDOWS_EULA": "windowsLicense",
"IOS_CONFIG_MDM_MODE": "iOSConfigMDMMode",
"IOS_CONFIG_APNS_MODE": "iOSConfigAPNSMode"
};
function promptErrorPolicyPlatform(errorMsg) {
var mainErrorMsgWrapper = "#platform-config-main-error-msg";
var mainErrorMsg = mainErrorMsgWrapper + " span";
$(mainErrorMsg).text(errorMsg);
$(mainErrorMsgWrapper).show();
}
$(document).ready(function () {
tinymce.init({
selector: "textarea",
height:500,
theme: "modern",
plugins: [
"autoresize",
"advlist autolink lists link image charmap print preview anchor",
"searchreplace visualblocks code fullscreen",
"insertdatetime image table contextmenu paste"
],
toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
});
var windowsConfigAPI = "/api/device-mgt/windows/v1.0/services/configuration";
invokerUtil.get(
windowsConfigAPI,
function (data) {
data = JSON.parse(data);
if (data != null && data.configuration != null) {
for (var i = 0; i < data.configuration.length; i++) {
var config = data.configuration[i];
if (config.name == configParams["NOTIFIER_FREQUENCY"]) {
$("input#windows-config-notifier-frequency").val(config.value / 1000);
} else if (config.name == configParams["WINDOWS_EULA"]) {
$("#windows-eula").val(config.value);
}
}
}
}, function (data) {
console.log(data);
}
);
$("select.select2[multiple=multiple]").select2({
tags: true
});
var errorMsgWrapperWindows = "#windows-config-error-msg";
var errorMsgWindows = "#windows-config-error-msg span";
var fileTypesWindows = ['jks'];
var notSupportedError = false;
var base64WindowsMDMCert = "";
var fileInputWindowsMDMCert = $('#windows-config-mdm-certificate');
var fileNameWindowsMDMCert = "";
var invalidFormatWindowsMDMCert = false;
$(fileInputWindowsMDMCert).change(function () {
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
$(errorMsgWindows).text("The File APIs are not fully supported in this browser.");
$(errorMsgWrapperWindows).removeClass("hidden");
notSupportedError = true;
return;
}
var file = fileInputWindowsMDMCert[0].files[0];
fileNameWindowsMDMCert = file.name;
var extension = file.name.split('.').pop().toLowerCase(),
isSuccess = fileTypesWindows.indexOf(extension) > -1;
if (isSuccess) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
base64WindowsMDMCert = event.target.result;
};
fileReader.readAsDataURL(file);
invalidFormatWindowsMDMCert = false;
} else {
base64MDMCert = "";
invalidFormatWindowsMDMCert = true;
}
});
$("button#save-windows-btn").click(function () {
var notifierFrequency = $("#windows-config-notifier-frequency").val();
var windowsLicense = tinyMCE.activeEditor.getContent();
if (!notifierFrequency) {
$(errorMsgWindows).text("Polling Interval is a required field. It cannot be empty.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else if (!windowsLicense) {
$(errorMsgWindows).text("License is a required field. It cannot be empty.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else if (!$.isNumeric(notifierFrequency)) {
$(errorMsgWindows).text("Provided Notifier frequency is invalid. It must be a number.");
$(errorMsgWrapperWindows).removeClass("hidden");
} else {
var addConfigFormData = {};
var configList = new Array();
var paramNotifierFrequency = {
"name": configParams["NOTIFIER_FREQUENCY"],
"value": String(notifierFrequency * 1000),
"contentType": "text"
};
var windowsEula = {
"name": configParams["WINDOWS_EULA"],
"value": windowsLicense,
"contentType": "text"
};
configList.push(paramNotifierFrequency);
configList.push(windowsEula);
addConfigFormData.type = platformTypeConstants["WINDOWS"];
addConfigFormData.configuration = configList;
var addConfigAPI = windowsConfigAPI;
invokerUtil.put(
addConfigAPI,
addConfigFormData,
function (data, textStatus, jqXHR) {
data = jqXHR.status;
if (data == 200) {
$("#config-save-form").addClass("hidden");
$("#record-created-msg").removeClass("hidden");
} else if (data == 500) {
$(errorMsg).text("Exception occurred at backend.");
} else if (data == 400) {
$(errorMsg).text("Configurations cannot be empty.");
} else {
$(errorMsg).text("An unexpected error occurred.");
}
$(errorMsgWrapperWindows).removeClass("hidden");
}, function (data) {
data = data.status;
if (data == 500) {
$(errorMsg).text("Exception occurred at backend.");
} else if (data == 403) {
$(errorMsg).text("Action was not permitted.");
} else {
$(errorMsg).text("An unexpected error occurred.");
}
$(errorMsgWrapper).removeClass("hidden");
}
);
}
});
}); | fixing the ui error when the windows plaform configuration not saved successfully
| components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.windows.platform.configuration/public/js/platform-configuration.js | fixing the ui error when the windows plaform configuration not saved successfully | <ide><path>omponents/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.windows.platform.configuration/public/js/platform-configuration.js
<ide> $("#config-save-form").addClass("hidden");
<ide> $("#record-created-msg").removeClass("hidden");
<ide> } else if (data == 500) {
<del> $(errorMsg).text("Exception occurred at backend.");
<add> $(errorMsgWindows).text("Exception occurred at backend.");
<ide> } else if (data == 400) {
<del> $(errorMsg).text("Configurations cannot be empty.");
<add> $(errorMsgWindows).text("Configurations cannot be empty.");
<ide> } else {
<del> $(errorMsg).text("An unexpected error occurred.");
<add> $(errorMsgWindows).text("An unexpected error occurred.");
<ide> }
<ide>
<ide> $(errorMsgWrapperWindows).removeClass("hidden");
<ide> }, function (data) {
<ide> data = data.status;
<ide> if (data == 500) {
<del> $(errorMsg).text("Exception occurred at backend.");
<add> $(errorMsgWindows).text("Exception occurred at backend.");
<ide> } else if (data == 403) {
<del> $(errorMsg).text("Action was not permitted.");
<add> $(errorMsgWindows).text("Action was not permitted.");
<ide> } else {
<del> $(errorMsg).text("An unexpected error occurred.");
<add> $(errorMsgWindows).text("An unexpected error occurred.");
<ide> }
<del> $(errorMsgWrapper).removeClass("hidden");
<add> $(errorMsgWrapperWindows).removeClass("hidden");
<ide> }
<ide> );
<ide> } |
|
Java | apache-2.0 | error: pathspec 'JECP-SE/src/com/annimon/jecp/se/ConsoleApplication.java' did not match any file(s) known to git
| 109da8bc8d7a72ab2089dc4879c63fe4e5e1785f | 1 | aNNiMON/JECP | /*
* Copyright 2014 Victor Melnik <[email protected]>, and
* individual contributors as indicated by the @authors tag.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.annimon.jecp.se;
import com.annimon.jecp.ConsoleApplicationListener;
import com.annimon.jecp.Jecp;
/**
* Main entry for console applications.
*
* @author aNNiMON
*/
public abstract class ConsoleApplication {
/**
* Standart constructor for apps.
*
* @param listener listens application-based events.
*/
public ConsoleApplication(ConsoleApplicationListener listener) {
Jecp.helper = new JecpHelper(this);
listener.onStartApp();
}
}
| JECP-SE/src/com/annimon/jecp/se/ConsoleApplication.java | Add ConsoleApplication Java SE | JECP-SE/src/com/annimon/jecp/se/ConsoleApplication.java | Add ConsoleApplication Java SE | <ide><path>ECP-SE/src/com/annimon/jecp/se/ConsoleApplication.java
<add>/*
<add> * Copyright 2014 Victor Melnik <[email protected]>, and
<add> * individual contributors as indicated by the @authors tag.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package com.annimon.jecp.se;
<add>
<add>import com.annimon.jecp.ConsoleApplicationListener;
<add>import com.annimon.jecp.Jecp;
<add>
<add>/**
<add> * Main entry for console applications.
<add> *
<add> * @author aNNiMON
<add> */
<add>public abstract class ConsoleApplication {
<add>
<add> /**
<add> * Standart constructor for apps.
<add> *
<add> * @param listener listens application-based events.
<add> */
<add> public ConsoleApplication(ConsoleApplicationListener listener) {
<add> Jecp.helper = new JecpHelper(this);
<add> listener.onStartApp();
<add> }
<add>} |
|
Java | epl-1.0 | e6810f24a1777584407303257525a410b7c51c62 | 0 | kwave/openhab2-addons,kwave/openhab2-addons,kwave/openhab2-addons | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zwave.internal.converter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.StopMoveType;
import org.eclipse.smarthome.core.library.types.UpDownType;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.zwave.handler.ZWaveThingHandler.ZWaveThingChannel;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveBatteryCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiLevelSwitchCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ZWaveBinarySwitchConverter class. Converter for communication with the {@link ZWaveBatteryCommandClass}. Implements
* polling of the battery status and receiving of battery events.
*
* @author Chris Jackson
* @author Jan-Willem Spuij
*/
public class ZWaveMultiLevelSwitchConverter extends ZWaveCommandClassConverter {
private static final Logger logger = LoggerFactory.getLogger(ZWaveMultiLevelSwitchConverter.class);
/**
* Constructor. Creates a new instance of the {@link ZWaveMultiLevelSwitchConverter} class.
*
*/
public ZWaveMultiLevelSwitchConverter() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public List<SerialMessage> executeRefresh(ZWaveThingChannel channel, ZWaveNode node) {
ZWaveMultiLevelSwitchCommandClass commandClass = (ZWaveMultiLevelSwitchCommandClass) node
.resolveCommandClass(ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, channel.getEndpoint());
if (commandClass == null) {
return null;
}
logger.debug("NODE {}: Generating poll message for {}, endpoint {}", node.getNodeId(),
commandClass.getCommandClass().getLabel(), channel.getEndpoint());
SerialMessage serialMessage = node.encapsulate(commandClass.getValueMessage(), commandClass,
channel.getEndpoint());
List<SerialMessage> response = new ArrayList<SerialMessage>(1);
response.add(serialMessage);
return response;
}
/**
* {@inheritDoc}
*/
@Override
public State handleEvent(ZWaveThingChannel channel, ZWaveCommandClassValueEvent event) {
int value = (int) event.getValue();
State state;
switch (channel.getDataType()) {
case PercentType:
if ("true".equalsIgnoreCase(channel.getArguments().get("invertPercent"))) {
state = new PercentType(100 - value);
} else {
state = new PercentType(value);
}
// If we read greater than 99%, then change it to 100%
// This just appears better in OH otherwise you can't get 100%!
if (((PercentType) state).intValue() >= 99) {
state = new PercentType(100);
}
break;
case OnOffType:
if (value == 0) {
state = OnOffType.OFF;
} else {
state = OnOffType.ON;
}
break;
case IncreaseDecreaseType:
state = null;
break;
default:
state = null;
logger.warn("No conversion in {} to {}", this.getClass().getSimpleName(), channel.getDataType());
break;
}
return state;
}
/**
* {@inheritDoc}
*/
@Override
public List<SerialMessage> receiveCommand(ZWaveThingChannel channel, ZWaveNode node, Command command) {
ZWaveMultiLevelSwitchCommandClass commandClass = (ZWaveMultiLevelSwitchCommandClass) node
.resolveCommandClass(ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, channel.getEndpoint());
SerialMessage serialMessage = null;
boolean restoreLastValue = "true".equalsIgnoreCase(channel.getArguments().get("restoreLastValue"));
if (command instanceof StopMoveType && (StopMoveType) command == StopMoveType.STOP) {
// Special handling for the STOP command
serialMessage = commandClass.stopLevelChangeMessage();
} else {
int value;
if (command instanceof OnOffType) {
if (restoreLastValue) {
value = command == OnOffType.ON ? 0xff : 0x00;
} else {
value = command == OnOffType.ON ? 0x63 : 0x00;
}
} else if (command instanceof PercentType) {
if ("true".equalsIgnoreCase(channel.getArguments().get("invertPercent"))) {
value = 100 - ((PercentType) command).intValue();
} else {
value = ((PercentType) command).intValue();
}
// zwave has a max vale of 99 for percentages.
if (value >= 100) {
value = 99;
}
} else if (command instanceof UpDownType) {
if ("true".equalsIgnoreCase(channel.getArguments().get("invertState"))) {
if (command == UpDownType.UP) {
command = UpDownType.DOWN;
} else {
command = UpDownType.UP;
}
}
value = command != UpDownType.DOWN ? 0x63 : 0x00;
} else {
logger.warn("NODE {}: No conversion for channel {}", node.getNodeId(), channel.getUID());
return null;
}
logger.trace("NODE {}: Converted command '{}' to value {} for channel = {}, endpoint = {}.",
node.getNodeId(), command.toString(), value, channel.getUID(), channel.getEndpoint());
serialMessage = commandClass.setValueMessage(value);
}
// encapsulate the message in case this is a multi-instance node
serialMessage = node.encapsulate(serialMessage, commandClass, channel.getEndpoint());
if (serialMessage == null) {
logger.warn("Generating message failed for command class = {}, node = {}, endpoint = {}",
commandClass.getCommandClass().getLabel(), node.getNodeId(), channel.getEndpoint());
return null;
}
// Queue the command
List<SerialMessage> messages = new ArrayList<SerialMessage>(2);
messages.add(serialMessage);
// Poll an update once we've sent the command
messages.add(node.encapsulate(commandClass.getValueMessage(), commandClass, channel.getEndpoint()));
return messages;
}
}
| addons/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/ZWaveMultiLevelSwitchConverter.java | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zwave.internal.converter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.StopMoveType;
import org.eclipse.smarthome.core.library.types.UpDownType;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.zwave.handler.ZWaveThingHandler.ZWaveThingChannel;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveBatteryCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiLevelSwitchCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ZWaveBinarySwitchConverter class. Converter for communication with the {@link ZWaveBatteryCommandClass}. Implements
* polling of the battery status and receiving of battery events.
*
* @author Chris Jackson
* @author Jan-Willem Spuij
*/
public class ZWaveMultiLevelSwitchConverter extends ZWaveCommandClassConverter {
private static final Logger logger = LoggerFactory.getLogger(ZWaveMultiLevelSwitchConverter.class);
/**
* Constructor. Creates a new instance of the {@link ZWaveMultiLevelSwitchConverter} class.
*
*/
public ZWaveMultiLevelSwitchConverter() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public List<SerialMessage> executeRefresh(ZWaveThingChannel channel, ZWaveNode node) {
ZWaveMultiLevelSwitchCommandClass commandClass = (ZWaveMultiLevelSwitchCommandClass) node
.resolveCommandClass(ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, channel.getEndpoint());
if (commandClass == null) {
return null;
}
logger.debug("NODE {}: Generating poll message for {}, endpoint {}", node.getNodeId(),
commandClass.getCommandClass().getLabel(), channel.getEndpoint());
SerialMessage serialMessage = node.encapsulate(commandClass.getValueMessage(), commandClass,
channel.getEndpoint());
List<SerialMessage> response = new ArrayList<SerialMessage>(1);
response.add(serialMessage);
return response;
}
/**
* {@inheritDoc}
*/
@Override
public State handleEvent(ZWaveThingChannel channel, ZWaveCommandClassValueEvent event) {
int value = (int) event.getValue();
State state;
switch (channel.getDataType()) {
case PercentType:
if ("true".equalsIgnoreCase(channel.getArguments().get("invertPercent"))) {
state = new PercentType(100 - value);
} else {
state = new PercentType(value);
}
// If we read greater than 99%, then change it to 100%
// This just appears better in OH otherwise you can't get 100%!
if (((PercentType) state).intValue() >= 99) {
state = new PercentType(100);
}
break;
case OnOffType:
if (value == 0) {
state = OnOffType.OFF;
} else {
state = OnOffType.ON;
}
break;
case IncreaseDecreaseType:
state = null;
break;
default:
state = null;
logger.warn("No conversion in {} to {}", this.getClass().getSimpleName(), channel.getDataType());
break;
}
return state;
}
/**
* {@inheritDoc}
*/
@Override
public List<SerialMessage> receiveCommand(ZWaveThingChannel channel, ZWaveNode node, Command command) {
ZWaveMultiLevelSwitchCommandClass commandClass = (ZWaveMultiLevelSwitchCommandClass) node
.resolveCommandClass(ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, channel.getEndpoint());
SerialMessage serialMessage = null;
boolean restoreLastValue = "true".equalsIgnoreCase(channel.getArguments().get("restoreLastValue"));
if (command instanceof StopMoveType && (StopMoveType) command == StopMoveType.STOP) {
// Special handling for the STOP command
serialMessage = commandClass.stopLevelChangeMessage();
} else {
int value;
if (command instanceof OnOffType) {
if (restoreLastValue) {
value = command == OnOffType.ON ? 0xff : 0x00;
} else {
value = command == OnOffType.ON ? 0x63 : 0x00;
}
} else if (command instanceof PercentType) {
if ("true".equalsIgnoreCase(channel.getArguments().get("invertPercent"))) {
value = 100 - ((PercentType) command).intValue();
} else {
value = ((PercentType) command).intValue();
}
} else if (command instanceof UpDownType) {
if ("true".equalsIgnoreCase(channel.getArguments().get("invertState"))) {
if (command == UpDownType.UP) {
command = UpDownType.DOWN;
} else {
command = UpDownType.UP;
}
}
value = command != UpDownType.DOWN ? 0x63 : 0x00;
} else {
logger.warn("NODE {}: No conversion for channel {}", node.getNodeId(), channel.getUID());
return null;
}
logger.trace("NODE {}: Converted command '{}' to value {} for channel = {}, endpoint = {}.",
node.getNodeId(), command.toString(), value, channel.getUID(), channel.getEndpoint());
serialMessage = commandClass.setValueMessage(value);
}
// encapsulate the message in case this is a multi-instance node
serialMessage = node.encapsulate(serialMessage, commandClass, channel.getEndpoint());
if (serialMessage == null) {
logger.warn("Generating message failed for command class = {}, node = {}, endpoint = {}",
commandClass.getCommandClass().getLabel(), node.getNodeId(), channel.getEndpoint());
return null;
}
// Queue the command
List<SerialMessage> messages = new ArrayList<SerialMessage>(2);
messages.add(serialMessage);
// Poll an update once we've sent the command
messages.add(node.encapsulate(commandClass.getValueMessage(), commandClass, channel.getEndpoint()));
return messages;
}
}
| Don't set values over 99 for zwave percent commands
Signed-off-by: digitaldan <[email protected]>
| addons/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/ZWaveMultiLevelSwitchConverter.java | Don't set values over 99 for zwave percent commands | <ide><path>ddons/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/ZWaveMultiLevelSwitchConverter.java
<ide> } else {
<ide> value = ((PercentType) command).intValue();
<ide> }
<add> // zwave has a max vale of 99 for percentages.
<add> if (value >= 100) {
<add> value = 99;
<add> }
<ide> } else if (command instanceof UpDownType) {
<ide> if ("true".equalsIgnoreCase(channel.getArguments().get("invertState"))) {
<ide> if (command == UpDownType.UP) { |
|
Java | apache-2.0 | 468867b6f16fefccff20a8958f85bda93d3e6a73 | 0 | michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3 | package hex;
import hex.genmodel.utils.DistributionFamily;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import water.*;
import water.fvec.*;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import water.test.dummy.DummyModel;
import water.test.dummy.DummyModelBuilder;
import water.test.dummy.DummyModelParameters;
import water.test.dummy.MessageInstallAction;
import water.util.ReflectionUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*;
import static water.TestUtil.*;
import static water.util.RandomUtils.getRNG;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class ModelBuilderTest {
@Rule
public transient TemporaryFolder tmp = new TemporaryFolder();
@Rule
public transient ExpectedException ee = ExpectedException.none();
@Test
public void testRebalancePubDev5400() {
try {
Scope.enter();
// create a frame where only the last chunk has data and the rest is empty
final int nChunks = H2O.NUMCPUS;
final int nRows = nChunks * 1000;
double[] colA = new double[nRows];
String[] resp = new String[nRows];
for (int i = 0; i < colA.length; i++) {
colA[i] = i % 7;
resp[i] = i % 3 == 0 ? "A" : "B";
}
long[] layout = new long[nChunks];
layout[nChunks - 1] = colA.length;
final Frame train = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, colA)
.withDataForCol(1, resp)
.withChunkLayout(layout)
.build());
assertEquals(nChunks, train.anyVec().nChunks());
assertEquals(colA.length, train.numRows());
DummyModelParameters parms = new DummyModelParameters("Rebalance Test", Key.make( "rebalance-test"));
parms._train = train._key;
ModelBuilder<?, ?, ?> mb = new DummyModelBuilder(parms);
// the frame looks ideal (it has as many chunks as desired)
assertEquals(nChunks, mb.desiredChunks(train, true));
// expensive init - should include rebalance
mb.init(true);
// check that dataset was rebalanced
long[] espc = mb.train().anyVec().espc();
assertEquals(nChunks + 1, espc.length);
assertEquals(nRows, espc[nChunks]);
for (int i = 0; i < espc.length; i++)
assertEquals(i * 1000, espc[i]);
} finally {
Scope.exit();
}
}
@Test
public void testRebalanceMulti() {
org.junit.Assume.assumeTrue(H2O.getCloudSize() > 1);
try {
Scope.enter();
double[] colA = new double[1000000];
String[] resp = new String[colA.length];
for (int i = 0; i < colA.length; i++) {
colA[i] = i % 7;
resp[i] = i % 3 == 0 ? "A" : "B";
}
final Frame train = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, colA)
.withDataForCol(1, resp)
.withChunkLayout(colA.length) // single chunk
.build());
assertEquals(1, train.anyVec().nChunks());
DummyModelParameters parms = new DummyModelParameters("Rebalance Test", Key.make( "rebalance-test"));
parms._train = train._key;
ModelBuilder<?, ?, ?> mb = new DummyModelBuilder(parms) {
@Override
protected String getSysProperty(String name, String def) {
if (name.equals("rebalance.ratio.multi"))
return "0.5";
if (name.equals("rebalance.enableMulti"))
return "true";
if (name.startsWith(H2O.OptArgs.SYSTEM_PROP_PREFIX + "rebalance"))
throw new IllegalStateException("Unexpected property: " + name);
return super.getSysProperty(name, def);
}
};
// the rebalance logic should spread the Frame across the whole cluster (>> single node CPUs)
final int desiredChunks = mb.desiredChunks(train, false);
assertTrue(desiredChunks > 4 * H2O.NUMCPUS);
// expensive init - should include rebalance
mb.init(true);
// check that dataset was rebalanced
final int rebalancedChunks = mb.train().anyVec().nonEmptyChunks();
assertEquals(desiredChunks, rebalancedChunks);
} finally {
Scope.exit();
}
}
@Test
public void testWorkSpaceInit() {
DummyModelBuilder builder = new DummyModelBuilder(new DummyModelParameters());
// workspace is initialized upon builder instantiation
ModelBuilder.Workspace workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace);
assertNull(workspace.getToDelete(false));
// cheap init keeps workspace unchanged
builder.init(false);
workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace);
assertNull(workspace.getToDelete(false));
// it is not possible to get "to delete" structure in for expensive operations
try {
workspace.getToDelete(true);
fail("Exception expected");
} catch (IllegalStateException e) {
assertEquals(
"ModelBuilder was not correctly initialized. Expensive phase requires field `_toDelete` to be non-null. " +
"Does your implementation of init method call super.init(true) or alternatively initWorkspace(true)?",
e.getMessage()
);
}
// expensive init will switch the workspace and let us get "to delete" for expensive ops
builder.init(true);
workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace.getToDelete(true));
}
@Test
public void testMakeUnknownModel() {
try {
ModelBuilder.make("invalid", null, null);
fail();
} catch (IllegalStateException e) {
// core doesn't have any algos but depending on the order of tests' execution DummyModelBuilder might already be registered
assertTrue( e.getMessage().startsWith("Algorithm 'invalid' is not registered. Available algos: ["));
}
}
@Test
public void testMakeFromModelParams() {
DummyModelParameters params = new DummyModelParameters();
ModelBuilder modelBuilder = ModelBuilder.make(params);
assertNotNull(modelBuilder._job);
assertNotNull(modelBuilder._result);
assertNotSame(modelBuilder._parms, params);
}
@Test
public void testMakeFromParamsAndKey() {
DummyModelParameters params = new DummyModelParameters();
Key<Model> mKey = Key.make();
ModelBuilder modelBuilder = ModelBuilder.make(params, mKey);
assertNotNull(modelBuilder._job);
assertEquals(modelBuilder._job._result, mKey);
assertEquals(mKey, modelBuilder._result);
assertNotSame(modelBuilder._parms, params);
}
@Test
public void testScoreReorderedDomain() {
Frame train = null, test = null, scored = null;
Model model = null;
try {
train = new TestFrameBuilder()
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar(0, 1))
.withDataForCol(1, ar("A", "B"))
.build();
test = new TestFrameBuilder()
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar(0, 1))
.withDataForCol(1, ar("A", "B"))
.withDomain(1, ar("B", "A"))
.build();
assertFalse(Arrays.equals(train.vec(1).domain(), test.vec(1).domain()));
DummyModelParameters p = new DummyModelParameters("Dummy 1", Key.make("dummny-1"));
p._makeModel = true;
p._train = train._key;
p._response_column = "col_1";
DummyModelBuilder bldr = new DummyModelBuilder(p);
model = bldr.trainModel().get();
scored = model.score(test);
//predict column should have the same domain as the target column of the scored frame
assertArrayEquals(new String[]{"B", "A"}, scored.vec(0).domain());
} finally {
if (model != null)
model.remove();
if (train != null)
train.remove();
if (test != null)
test.remove();
if (scored != null)
scored.remove();
}
}
@Test
public void testExportCheckpointsWriteCheck() throws IOException {
try {
Scope.enter();
File dummyFile = tmp.newFile("dummy");
Frame train = TestFrameCatalog.oneChunkFewRows();
// 1. Validation is only down
DummyModelParameters failingParms = new DummyModelParameters("Failing Dummy", Key.make("dummny-failing"));
failingParms._export_checkpoints_dir = dummyFile.getAbsolutePath();
failingParms._train = train._key;
failingParms._response_column = train.name(0);
DummyModelBuilder failingBuilder = new DummyModelBuilder(failingParms);
assertEquals(
"ERRR on field: _export_checkpoints_dir: Checkpoints directory path must point to a writable path.\n",
failingBuilder.validationErrors()
);
// 2. Now test that CV model will do no validation
DummyModelParameters cvParams = new DummyModelParameters("Failing Dummy", Key.make("dummny-failing"));
cvParams._export_checkpoints_dir = dummyFile.getAbsolutePath();
cvParams._train = train._key;
cvParams._response_column = train.name(0);
cvParams._is_cv_model = true; // Emulate CV
DummyModelBuilder cvBuilder = new DummyModelBuilder(cvParams);
assertEquals("", cvBuilder.validationErrors()); // shouldn't fail
} finally {
Scope.exit();
}
}
@Test
public void testUsedColumns() {
String[] trainNames = new String[] {
"c1", "c2", "c3", "c4", "c5", "response"
};
DummyModelParameters params = new DummyModelParameters();
params._dummy_string_array_param = new String[] { "c1" };
params._dummy_string_param = "c2";
assertEquals(
"no columns used", emptySet(), params.getUsedColumns(trainNames));
params._column_param = "invalid";
assertEquals(
"invalid column name not used", emptySet(), params.getUsedColumns(trainNames)
);
params._column_param = "response";
assertEquals(
"columns from simple param",
new HashSet<>(singletonList("response")), params.getUsedColumns(trainNames)
);
params._column_param = null;
params._column_list_param = new String[] { "invalid", "c4", "c5" };
assertEquals(
"columns from array param",
new HashSet<>(asList("c4", "c5")), params.getUsedColumns(trainNames)
);
params._column_param = "response";
assertEquals(
"columns from multiple params combined",
new HashSet<>(asList("c4", "c5", "response")), params.getUsedColumns(trainNames)
);
}
@Test
public void testTrainModelNestedExecutesOnExceptionalCompletionSynchronously() {
Key proofKey = Key.make();
try {
Scope.enter();
Frame trainingFrame = TestFrameCatalog.oneChunkFewRows();
DummyModelParameters params = new DummyModelParameters();
params._response_column = trainingFrame.name(0);
params._train = trainingFrame._key;
params._cancel_job = true;
params._on_exception_action = new DelayedMessageInstallAction(proofKey, "onExceptionalCompletion", 1000);
ee.expect(Job.JobCancelledException.class);
try {
new DummyModelBuilder(params).trainModelNested(trainingFrame);
} finally {
assertEquals("Computed onExceptionalCompletion", DKV.getGet(proofKey).toString());
}
} finally {
Scope.exit();
DKV.remove(proofKey);
}
}
private static class DelayedMessageInstallAction extends MessageInstallAction {
private final int _delay_millis;
DelayedMessageInstallAction(Key trgt, String msg, int delayMillis) {
super(trgt, msg);
_delay_millis = delayMillis;
}
@Override
protected String run(DummyModelParameters parms) {
try {
Thread.sleep(_delay_millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return super.run(parms);
}
}
@Test
public void testFoldColumnHaveExtraLevels() {
DummyModel model = null;
try {
Scope.enter();
Frame trainingFrame = TestFrameCatalog.oneChunkFewRows();
Vec fold = Scope.track(ivec(1, 3, 1));
fold.setDomain(new String[]{"NoDataFold0", "fold1", "NoDataFold2", "fold3", "NoDataFold4"});
DKV.put(fold);
trainingFrame.add("Fold", fold);
DKV.put(trainingFrame);
DummyModelParameters params = new DummyModelParameters();
params._response_column = "col_3";
params._train = trainingFrame._key;
params._fold_column = "Fold";
params._makeModel = true;
model = new DummyModelBuilder(params).trainModel().get();
Scope.track_generic(model);
assertEquals(2, model._output._cross_validation_models.length);
} finally {
if (model != null)
model.deleteCrossValidationModels();
Scope.exit();
}
}
@Test
public void testMakeHoldoutPredictionCombiner() {
assertFalse(
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, 0) instanceof ModelBuilder.ApproximatingHoldoutPredictionCombiner
);
assertTrue(
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, 4) instanceof ModelBuilder.ApproximatingHoldoutPredictionCombiner
);
ee.expectMessage("Precision cannot be negative, got precision = -42");
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, -42);
}
@Test
public void testApproximatingHoldoutPredictionCombiner() {
try {
Scope.enter();
Vec v = Vec.makeVec(ard(0, 1.0, 0.1, 0.99994, 0.99995, 1e-5, 0.123456789), Vec.newKey());
Scope.track(v);
Frame approx = new ModelBuilder.ApproximatingHoldoutPredictionCombiner(1, 1, 4)
.doAll(Vec.T_NUM, v).outputFrame();
Scope.track(approx);
Vec expected = Vec.makeVec(ard(0, 1.0, 0.1, 0.9999, 1.0, 0, 0.1235), Vec.newKey());
assertVecEquals(expected, approx.vec(0), 0);
} finally {
Scope.exit();
}
}
@Test
public void testApproximatingHoldoutPredictionCombinerProducesCSChunks() {
try {
Scope.enter();
Vec v = randomProbabilitiesVec(42, 100_000, 20);
Scope.track(v);
checkApproximatingHoldoutPredictionCombiner(v, 8, 2, 0.2);
checkApproximatingHoldoutPredictionCombiner(v, 4, 4, 0.2);
checkApproximatingHoldoutPredictionCombiner(v, 2, 8, 0.5);
} finally {
Scope.exit();
}
}
private static void checkApproximatingHoldoutPredictionCombiner(Vec v, int precision, int expectedMemoryRatio, double delta) {
Vec approx = new ModelBuilder.ApproximatingHoldoutPredictionCombiner(1, 1, precision)
.doAll(Vec.T_NUM, v).outputFrame().vec(0);
Scope.track(approx);
assertEquals(expectedMemoryRatio, v.byteSize() / (double) approx.byteSize(), delta);
for (int i = 0; i < approx.nChunks(); i++) {
assertTrue(approx.chunkForChunkIdx(i) instanceof CSChunk);
}
}
private static Vec randomProbabilitiesVec(final long seed, final long len, final int nChunks) {
Vec v = Vec.makeConN(len, nChunks);
new MRTask() {
@Override public void map(Chunk c) {
final long chunk_seed = seed + c.start();
for (int i = 0; i < c._len; i++) {
double rnd = getRNG(chunk_seed + i).nextDouble();
c.set(i, rnd);
}
}
}.doAll(v);
return v;
}
}
| h2o-core/src/test/java/hex/ModelBuilderTest.java | package hex;
import hex.genmodel.utils.DistributionFamily;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import water.*;
import water.fvec.*;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import water.test.dummy.DummyModel;
import water.test.dummy.DummyModelBuilder;
import water.test.dummy.DummyModelParameters;
import water.test.dummy.MessageInstallAction;
import water.util.ReflectionUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*;
import static water.TestUtil.*;
import static water.util.RandomUtils.getRNG;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class ModelBuilderTest {
@Rule
public transient TemporaryFolder tmp = new TemporaryFolder();
@Rule
public transient ExpectedException ee = ExpectedException.none();
@Test
public void testRebalancePubDev5400() {
try {
Scope.enter();
// create a frame where only the last chunk has data and the rest is empty
final int nChunks = H2O.NUMCPUS;
final int nRows = nChunks * 1000;
double[] colA = new double[nRows];
String[] resp = new String[nRows];
for (int i = 0; i < colA.length; i++) {
colA[i] = i % 7;
resp[i] = i % 3 == 0 ? "A" : "B";
}
long[] layout = new long[nChunks];
layout[nChunks - 1] = colA.length;
final Frame train = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, colA)
.withDataForCol(1, resp)
.withChunkLayout(layout)
.build());
assertEquals(nChunks, train.anyVec().nChunks());
assertEquals(colA.length, train.numRows());
DummyModelParameters parms = new DummyModelParameters("Rebalance Test", Key.make( "rebalance-test"));
parms._train = train._key;
ModelBuilder<?, ?, ?> mb = new DummyModelBuilder(parms);
// the frame looks ideal (it has as many chunks as desired)
assertEquals(nChunks, mb.desiredChunks(train, true));
// expensive init - should include rebalance
mb.init(true);
// check that dataset was rebalanced
long[] espc = mb.train().anyVec().espc();
assertEquals(nChunks + 1, espc.length);
assertEquals(nRows, espc[nChunks]);
for (int i = 0; i < espc.length; i++)
assertEquals(i * 1000, espc[i]);
} finally {
Scope.exit();
}
}
@Test
public void testRebalanceMulti() {
org.junit.Assume.assumeTrue(H2O.getCloudSize() > 1);
try {
Scope.enter();
double[] colA = new double[1000000];
String[] resp = new String[colA.length];
for (int i = 0; i < colA.length; i++) {
colA[i] = i % 7;
resp[i] = i % 3 == 0 ? "A" : "B";
}
final Frame train = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, colA)
.withDataForCol(1, resp)
.withChunkLayout(colA.length) // single chunk
.build());
assertEquals(1, train.anyVec().nChunks());
DummyModelParameters parms = new DummyModelParameters("Rebalance Test", Key.make( "rebalance-test"));
parms._train = train._key;
ModelBuilder<?, ?, ?> mb = new DummyModelBuilder(parms) {
@Override
protected String getSysProperty(String name, String def) {
if (name.equals("rebalance.ratio.multi"))
return "0.5";
if (name.equals("rebalance.enableMulti"))
return "true";
if (name.startsWith(H2O.OptArgs.SYSTEM_PROP_PREFIX + "rebalance"))
throw new IllegalStateException("Unexpected property: " + name);
return super.getSysProperty(name, def);
}
};
// the rebalance logic should spread the Frame across the whole cluster (>> single node CPUs)
final int desiredChunks = mb.desiredChunks(train, false);
assertTrue(desiredChunks > 4 * H2O.NUMCPUS);
// expensive init - should include rebalance
mb.init(true);
// check that dataset was rebalanced
final int rebalancedChunks = mb.train().anyVec().nonEmptyChunks();
assertEquals(desiredChunks, rebalancedChunks);
} finally {
Scope.exit();
}
}
@Test
public void testWorkSpaceInit() {
DummyModelBuilder builder = new DummyModelBuilder(new DummyModelParameters());
// workspace is initialized upon builder instantiation
ModelBuilder.Workspace workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace);
assertNull(workspace.getToDelete(false));
// cheap init keeps workspace unchanged
builder.init(false);
workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace);
assertNull(workspace.getToDelete(false));
// it is not possible to get "to delete" structure in for expensive operations
try {
workspace.getToDelete(true);
fail("Exception expected");
} catch (IllegalStateException e) {
assertEquals(
"ModelBuilder was not correctly initialized. Expensive phase requires field `_toDelete` to be non-null. " +
"Does your implementation of init method call super.init(true) or alternatively initWorkspace(true)?",
e.getMessage()
);
}
// expensive init will switch the workspace and let us get "to delete" for expensive ops
builder.init(true);
workspace = ReflectionUtils.getFieldValue(builder, "_workspace");
assertNotNull(workspace.getToDelete(true));
}
@Test
public void testMakeUnknownModel() {
try {
ModelBuilder.make("invalid", null, null);
fail();
} catch (IllegalStateException e) {
// core doesn't have any algos but depending on the order of tests' execution DummyModelBuilder might already be registered
assertTrue( e.getMessage().startsWith("Algorithm 'invalid' is not registered. Available algos: ["));
}
}
@Test
public void testMakeFromModelParams() {
DummyModelParameters params = new DummyModelParameters();
ModelBuilder modelBuilder = ModelBuilder.make(params);
assertNotNull(modelBuilder._job);
assertNotNull(modelBuilder._result);
assertNotSame(modelBuilder._parms, params);
}
@Test
public void testMakeFromParamsAndKey() {
DummyModelParameters params = new DummyModelParameters();
Key<Model> mKey = Key.make();
ModelBuilder modelBuilder = ModelBuilder.make(params, mKey);
assertNotNull(modelBuilder._job);
assertEquals(modelBuilder._job._result, mKey);
assertEquals(mKey, modelBuilder._result);
assertNotSame(modelBuilder._parms, params);
}
@Test
public void testScoreReorderedDomain() {
Frame train = null, test = null, scored = null;
Model model = null;
try {
train = new TestFrameBuilder()
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar(0, 1))
.withDataForCol(1, ar("A", "B"))
.build();
test = new TestFrameBuilder()
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar(0, 1))
.withDataForCol(1, ar("A", "B"))
.withDomain(1, ar("B", "A"))
.build();
assertFalse(Arrays.equals(train.vec(1).domain(), test.vec(1).domain()));
DummyModelParameters p = new DummyModelParameters("Dummy 1", Key.make("dummny-1"));
p._makeModel = true;
p._train = train._key;
p._response_column = "col_1";
DummyModelBuilder bldr = new DummyModelBuilder(p);
model = bldr.trainModel().get();
scored = model.score(test);
//predict column should have the same domain as the target column of the scored frame
assertArrayEquals(new String[]{"B", "A"}, scored.vec(0).domain());
} finally {
if (model != null)
model.remove();
if (train != null)
train.remove();
if (test != null)
test.remove();
if (scored != null)
scored.remove();
}
}
@Test
public void testExportCheckpointsWriteCheck() throws IOException {
try {
Scope.enter();
File dummyFile = tmp.newFile("dummy");
Frame train = TestFrameCatalog.oneChunkFewRows();
// 1. Validation is only down
DummyModelParameters failingParms = new DummyModelParameters("Failing Dummy", Key.make("dummny-failing"));
failingParms._export_checkpoints_dir = dummyFile.getAbsolutePath();
failingParms._train = train._key;
failingParms._response_column = train.name(0);
DummyModelBuilder failingBuilder = new DummyModelBuilder(failingParms);
assertEquals(
"ERRR on field: _export_checkpoints_dir: Checkpoints directory path must point to a writable path.\n",
failingBuilder.validationErrors()
);
// 2. Now test that CV model will do no validation
DummyModelParameters cvParams = new DummyModelParameters("Failing Dummy", Key.make("dummny-failing"));
cvParams._export_checkpoints_dir = dummyFile.getAbsolutePath();
cvParams._train = train._key;
cvParams._response_column = train.name(0);
cvParams._is_cv_model = true; // Emulate CV
DummyModelBuilder cvBuilder = new DummyModelBuilder(cvParams);
assertEquals("", cvBuilder.validationErrors()); // shouldn't fail
} finally {
Scope.exit();
}
}
@Test
public void testUsedColumns() {
String[] trainNames = new String[] {
"c1", "c2", "c3", "c4", "c5", "response"
};
DummyModelParameters params = new DummyModelParameters();
params._dummy_string_array_param = new String[] { "c1" };
params._dummy_string_param = "c2";
assertEquals(
"no columns used", emptySet(), params.getUsedColumns(trainNames));
params._column_param = "invalid";
assertEquals(
"invalid column name not used", emptySet(), params.getUsedColumns(trainNames)
);
params._column_param = "response";
assertEquals(
"columns from simple param",
new HashSet<>(singletonList("response")), params.getUsedColumns(trainNames)
);
params._column_param = null;
params._column_list_param = new String[] { "invalid", "c4", "c5" };
assertEquals(
"columns from array param",
new HashSet<>(asList("c4", "c5")), params.getUsedColumns(trainNames)
);
params._column_param = "response";
assertEquals(
"columns from multiple params combined",
new HashSet<>(asList("c4", "c5", "response")), params.getUsedColumns(trainNames)
);
}
@Test
public void testTrainModelNestedExecutesOnExceptionalCompletionSynchronously() {
Key proofKey = Key.make();
try {
Scope.enter();
Frame trainingFrame = TestFrameCatalog.oneChunkFewRows();
DummyModelParameters params = new DummyModelParameters();
params._response_column = trainingFrame.name(0);
params._train = trainingFrame._key;
params._cancel_job = true;
params._on_exception_action = new DelayedMessageInstallAction(proofKey, "onExceptionalCompletion", 1000);
ee.expect(Job.JobCancelledException.class);
try {
new DummyModelBuilder(params).trainModelNested(trainingFrame);
} finally {
assertEquals("Computed onExceptionalCompletion", DKV.getGet(proofKey).toString());
}
} finally {
Scope.exit();
DKV.remove(proofKey);
}
}
private static class DelayedMessageInstallAction extends MessageInstallAction {
private final int _delay_millis;
DelayedMessageInstallAction(Key trgt, String msg, int delayMillis) {
super(trgt, msg);
_delay_millis = delayMillis;
}
@Override
protected String run(DummyModelParameters parms) {
try {
Thread.sleep(_delay_millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return super.run(parms);
}
}
@Test
public void testFoldColumnHaveExtraLevels() {
DummyModel model = null;
try {
Scope.enter();
Frame trainingFrame = TestFrameCatalog.oneChunkFewRows();
Vec fold = Scope.track(ivec(1, 3, 1));
fold.setDomain(new String[]{"NoDataFold0", "fold1", "NoDataFold2", "fold3", "NoDataFold4"});
DKV.put(fold);
trainingFrame.add("Fold", fold);
DKV.put(trainingFrame);
DummyModelParameters params = new DummyModelParameters();
params._response_column = "col_3";
params._train = trainingFrame._key;
params._fold_column = "Fold";
params._makeModel = true;
model = new DummyModelBuilder(params).trainModel().get();
Scope.track_generic(model);
assertEquals(2, model._output._cross_validation_models.length);
} finally {
if (model != null)
model.deleteCrossValidationModels();
Scope.exit();
}
}
@Test
public void testMakeHoldoutPredictionCombiner() {
assertFalse(
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, 0) instanceof ModelBuilder.ApproximatingHoldoutPredictionCombiner
);
assertTrue(
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, 4) instanceof ModelBuilder.ApproximatingHoldoutPredictionCombiner
);
ee.expectMessage("Precision cannot be negative, got precision = -42");
ModelBuilder.makeHoldoutPredictionCombiner(-1, -1, -42);
}
@Test
public void testApproximatingHoldoutPredictionCombiner() {
try {
Scope.enter();
Vec v = Vec.makeVec(ard(0, 1.0, 0.1, 0.99994, 0.99995, 1e-5, 0.123456789), Vec.newKey());
Scope.track(v);
Frame approx = new ModelBuilder.ApproximatingHoldoutPredictionCombiner(1, 1, 4)
.doAll(Vec.T_NUM, v).outputFrame();
Scope.track(approx);
Vec expected = Vec.makeVec(ard(0, 1.0, 0.1, 0.9999, 1.0, 0, 0.1235), Vec.newKey());
assertVecEquals(expected, approx.vec(0), 0);
} finally {
Scope.exit();
}
}
@Test
public void testApproximatingHoldoutPredictionCombinerProducesCSChunks() {
try {
Scope.enter();
Vec v = randomProbabilitiesVec(42, 100_000);
Scope.track(v);
checkApproximatingHoldoutPredictionCombiner(v, 8, 2, 0.2);
checkApproximatingHoldoutPredictionCombiner(v, 4, 4, 0.2);
checkApproximatingHoldoutPredictionCombiner(v, 2, 8, 0.5);
} finally {
Scope.exit();
}
}
private static void checkApproximatingHoldoutPredictionCombiner(Vec v, int precision, int expectedMemoryRatio, double delta) {
Vec approx = new ModelBuilder.ApproximatingHoldoutPredictionCombiner(1, 1, precision)
.doAll(Vec.T_NUM, v).outputFrame().vec(0);
Scope.track(approx);
assertEquals(expectedMemoryRatio, v.byteSize() / (double) approx.byteSize(), delta);
for (int i = 0; i < approx.nChunks(); i++) {
assertTrue(approx.chunkForChunkIdx(i) instanceof CSChunk);
}
}
private static Vec randomProbabilitiesVec(final long seed, final long len) {
Vec v = Vec.makeCon(0.0d, len);
new MRTask() {
@Override public void map(Chunk c) {
final long chunk_seed = seed + c.start();
for (int i = 0; i < c._len; i++) {
double rnd = getRNG(chunk_seed + i).nextDouble();
c.set(i, rnd);
}
}
}.doAll(v);
return v;
}
}
| Make ApproximatingHoldoutPredictionCombiner test reproducible
By using explic number of chunks
| h2o-core/src/test/java/hex/ModelBuilderTest.java | Make ApproximatingHoldoutPredictionCombiner test reproducible | <ide><path>2o-core/src/test/java/hex/ModelBuilderTest.java
<ide> public void testApproximatingHoldoutPredictionCombinerProducesCSChunks() {
<ide> try {
<ide> Scope.enter();
<del> Vec v = randomProbabilitiesVec(42, 100_000);
<add> Vec v = randomProbabilitiesVec(42, 100_000, 20);
<ide> Scope.track(v);
<ide>
<ide> checkApproximatingHoldoutPredictionCombiner(v, 8, 2, 0.2);
<ide> }
<ide> }
<ide>
<del> private static Vec randomProbabilitiesVec(final long seed, final long len) {
<del> Vec v = Vec.makeCon(0.0d, len);
<add> private static Vec randomProbabilitiesVec(final long seed, final long len, final int nChunks) {
<add> Vec v = Vec.makeConN(len, nChunks);
<ide> new MRTask() {
<ide> @Override public void map(Chunk c) {
<ide> final long chunk_seed = seed + c.start(); |
|
Java | mit | error: pathspec 'stag-library/src/main/java/com/vimeo/stag/KnownTypeAdapters.java' did not match any file(s) known to git
| 0712ed0d65cb353122c6853fd0a62be4ac8340ba | 1 | Flipkart/stag-java,vimeo/stag-java,vimeo/stag-java,Flipkart/stag-java,vimeo/stag-java,Flipkart/stag-java | package com.vimeo.stag;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class KnownTypeAdapters {
private static TypeAdapter stringMapTypeAdapter;
private static TypeAdapter mapTypeAdapter;
private static TypeAdapter stringToIntegerMapTypeAdapter;
public static <V> TypeAdapter getStringMapTypeAdapter(TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
if (null == stringMapTypeAdapter) {
stringMapTypeAdapter = new StringMapTypeAdapter<>(valueTypeAdapter, instantiater);
}
return stringMapTypeAdapter;
}
public static <K, V> TypeAdapter getMapTypeAdapter(TypeAdapter<K> keyTypeAdapter, TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
if (null == mapTypeAdapter) {
mapTypeAdapter = new MapTypeAdapter<>(keyTypeAdapter, valueTypeAdapter, instantiater);
}
return mapTypeAdapter;
}
public static TypeAdapter getStringToIntegerMapTypeAdapter(Instantiater<Map> instantiater) {
if (null == stringToIntegerMapTypeAdapter) {
stringToIntegerMapTypeAdapter = new StringToIntegerMapTypeAdapter(instantiater);
}
return stringToIntegerMapTypeAdapter;
}
private static class StringToIntegerMapTypeAdapter extends MapTypeAdapter<String, Integer> {
StringToIntegerMapTypeAdapter(Instantiater<Map> instantiater) {
super(null, null, instantiater);
}
@Override
public void write(JsonWriter writer, Map<String, Integer> value) throws IOException {
writer.beginObject();
for (java.util.HashMap.Entry<String, Integer> entry : value.entrySet()) {
writer.name(entry.getKey());
writer.value(entry.getValue());
}
writer.endObject();
}
@Override
public Map<String, Integer> read(JsonReader reader) throws IOException {
if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.skipValue();
return null;
}
reader.beginObject();
Map<String, Integer> object = new LinkedHashMap<>();
if (instantiater != null) {
object = instantiater.instantiate();
}
while (reader.hasNext()) {
com.google.gson.stream.JsonToken jsonToken = reader.peek();
if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
reader.skipValue();
continue;
}
if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.beginObject();
while (reader.hasNext()) {
com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
String key = reader.nextString();
Integer value = reader.nextInt();
Integer replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
}
reader.endObject();
} else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
reader.beginArray();
String key = reader.nextString();
Integer value = reader.nextInt();
Integer replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
reader.endArray();
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
return object;
}
}
private static class StringMapTypeAdapter<V> extends MapTypeAdapter<String, V> {
StringMapTypeAdapter(TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
super(null, valueTypeAdapter, instantiater);
}
@Override
public void write(JsonWriter writer, Map<String, V> value) throws IOException {
writer.beginObject();
for (java.util.HashMap.Entry<String, V> entry : value.entrySet()) {
writer.name(entry.getKey());
valueTypeAdapter.write(writer, entry.getValue());
}
writer.endObject();
}
@Override
public Map<String, V> read(JsonReader reader) throws IOException {
if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.skipValue();
return null;
}
reader.beginObject();
Map<String, V> object = new LinkedHashMap<>();
if (instantiater != null) {
object = instantiater.instantiate();
}
while (reader.hasNext()) {
com.google.gson.stream.JsonToken jsonToken = reader.peek();
if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
reader.skipValue();
continue;
}
if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.beginObject();
while (reader.hasNext()) {
com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
String key = reader.nextString();
V value = valueTypeAdapter.read(reader);
V replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
}
reader.endObject();
} else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
reader.beginArray();
String key = reader.nextString();
V value = valueTypeAdapter.read(reader);
V replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
reader.endArray();
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
return object;
}
}
public static class MapTypeAdapter<K, V> extends TypeAdapter<Map<K, V>> {
protected Instantiater<Map> instantiater;
protected TypeAdapter<V> valueTypeAdapter;
private TypeAdapter<K> keyTypeAdapter;
MapTypeAdapter(TypeAdapter<K> keyTypeAdapter, TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
this.keyTypeAdapter = keyTypeAdapter;
this.valueTypeAdapter = valueTypeAdapter;
this.instantiater = instantiater;
}
@Override
public void write(JsonWriter writer, Map<K, V> value) throws IOException {
boolean hasComplexKeys = false;
List<JsonElement> keys = new ArrayList<JsonElement>(value.size());
List<V> values = new ArrayList<>(value.size());
for (Map.Entry<K, V> entry : value.entrySet()) {
JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
keys.add(keyElement);
values.add(entry.getValue());
hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject();
}
if (hasComplexKeys) {
writer.beginArray();
for (int i = 0; i < keys.size(); i++) {
writer.beginArray(); // entry array
Streams.write(keys.get(i), writer);
valueTypeAdapter.write(writer, values.get(i));
writer.endArray();
}
writer.endArray();
} else {
writer.beginObject();
for (int i = 0; i < keys.size(); i++) {
JsonElement keyElement = keys.get(i);
writer.name(keyToString(keyElement));
valueTypeAdapter.write(writer, values.get(i));
}
writer.endObject();
}
}
@Override
public Map<K, V> read(JsonReader reader) throws IOException {
if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.skipValue();
return null;
}
reader.beginObject();
Map<K, V> object = new LinkedHashMap<>();
if (instantiater != null) {
object = instantiater.instantiate();
}
while (reader.hasNext()) {
com.google.gson.stream.JsonToken jsonToken = reader.peek();
if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
reader.skipValue();
continue;
}
if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.beginObject();
while (reader.hasNext()) {
com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
K key = keyTypeAdapter.read(reader);
V value = valueTypeAdapter.read(reader);
V replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
}
reader.endObject();
} else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
reader.beginArray();
K key = keyTypeAdapter.read(reader);
V value = valueTypeAdapter.read(reader);
V replaced = object.put(key, value);
if (replaced != null) {
throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
}
reader.endArray();
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
return object;
}
private String keyToString(JsonElement keyElement) {
if (keyElement.isJsonPrimitive()) {
JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
if (primitive.isNumber()) {
return String.valueOf(primitive.getAsNumber());
} else if (primitive.isBoolean()) {
return Boolean.toString(primitive.getAsBoolean());
} else if (primitive.isString()) {
return primitive.getAsString();
} else {
throw new AssertionError();
}
} else if (keyElement.isJsonNull()) {
return "null";
} else {
throw new AssertionError();
}
}
}
public static class ListTypeAdapter<T> extends TypeAdapter<List<T>> {
private TypeAdapter<T> valueTypeAdapter;
private Instantiater<List> instantiater;
public ListTypeAdapter(TypeAdapter<T> valueTypeAdapter, Instantiater<List> instantiater) {
this.valueTypeAdapter = valueTypeAdapter;
this.instantiater = instantiater;
}
@Override
public void write(JsonWriter writer, List<T> value) throws IOException {
writer.beginArray();
for (T item : value) {
valueTypeAdapter.write(writer, item);
}
writer.endArray();
}
@Override
public List<T> read(JsonReader reader) throws IOException {
if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
reader.skipValue();
return null;
}
reader.beginObject();
List<T> object = new ArrayList<>();
if (instantiater != null) {
object = instantiater.instantiate();
}
while (reader.hasNext()) {
com.google.gson.stream.JsonToken jsonToken = reader.peek();
if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
reader.skipValue();
continue;
}
if (jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
object.add(valueTypeAdapter.read(reader));
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
return object;
}
}
} | stag-library/src/main/java/com/vimeo/stag/KnownTypeAdapters.java | all known typeadapters
| stag-library/src/main/java/com/vimeo/stag/KnownTypeAdapters.java | all known typeadapters | <ide><path>tag-library/src/main/java/com/vimeo/stag/KnownTypeAdapters.java
<add>package com.vimeo.stag;
<add>
<add>import com.google.gson.JsonElement;
<add>import com.google.gson.JsonPrimitive;
<add>import com.google.gson.TypeAdapter;
<add>import com.google.gson.internal.Streams;
<add>import com.google.gson.stream.JsonReader;
<add>import com.google.gson.stream.JsonWriter;
<add>
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.LinkedHashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>public class KnownTypeAdapters {
<add>
<add> private static TypeAdapter stringMapTypeAdapter;
<add> private static TypeAdapter mapTypeAdapter;
<add> private static TypeAdapter stringToIntegerMapTypeAdapter;
<add>
<add> public static <V> TypeAdapter getStringMapTypeAdapter(TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
<add> if (null == stringMapTypeAdapter) {
<add> stringMapTypeAdapter = new StringMapTypeAdapter<>(valueTypeAdapter, instantiater);
<add> }
<add> return stringMapTypeAdapter;
<add> }
<add>
<add> public static <K, V> TypeAdapter getMapTypeAdapter(TypeAdapter<K> keyTypeAdapter, TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
<add> if (null == mapTypeAdapter) {
<add> mapTypeAdapter = new MapTypeAdapter<>(keyTypeAdapter, valueTypeAdapter, instantiater);
<add> }
<add> return mapTypeAdapter;
<add> }
<add>
<add> public static TypeAdapter getStringToIntegerMapTypeAdapter(Instantiater<Map> instantiater) {
<add> if (null == stringToIntegerMapTypeAdapter) {
<add> stringToIntegerMapTypeAdapter = new StringToIntegerMapTypeAdapter(instantiater);
<add> }
<add> return stringToIntegerMapTypeAdapter;
<add> }
<add>
<add> private static class StringToIntegerMapTypeAdapter extends MapTypeAdapter<String, Integer> {
<add>
<add> StringToIntegerMapTypeAdapter(Instantiater<Map> instantiater) {
<add> super(null, null, instantiater);
<add> }
<add>
<add> @Override
<add> public void write(JsonWriter writer, Map<String, Integer> value) throws IOException {
<add> writer.beginObject();
<add> for (java.util.HashMap.Entry<String, Integer> entry : value.entrySet()) {
<add> writer.name(entry.getKey());
<add> writer.value(entry.getValue());
<add> }
<add> writer.endObject();
<add> }
<add>
<add> @Override
<add> public Map<String, Integer> read(JsonReader reader) throws IOException {
<add> if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
<add> reader.nextNull();
<add> return null;
<add> }
<add> if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.skipValue();
<add> return null;
<add> }
<add> reader.beginObject();
<add>
<add> Map<String, Integer> object = new LinkedHashMap<>();
<add> if (instantiater != null) {
<add> object = instantiater.instantiate();
<add> }
<add>
<add> while (reader.hasNext()) {
<add> com.google.gson.stream.JsonToken jsonToken = reader.peek();
<add> if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
<add> reader.skipValue();
<add> continue;
<add> }
<add>
<add> if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.beginObject();
<add> while (reader.hasNext()) {
<add> com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
<add> String key = reader.nextString();
<add> Integer value = reader.nextInt();
<add> Integer replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> }
<add> reader.endObject();
<add> } else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
<add> reader.beginArray();
<add> while (reader.hasNext()) {
<add> reader.beginArray();
<add> String key = reader.nextString();
<add> Integer value = reader.nextInt();
<add> Integer replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> reader.endArray();
<add> }
<add> reader.endArray();
<add> } else {
<add> reader.skipValue();
<add> }
<add> }
<add>
<add> reader.endObject();
<add> return object;
<add> }
<add> }
<add>
<add> private static class StringMapTypeAdapter<V> extends MapTypeAdapter<String, V> {
<add>
<add> StringMapTypeAdapter(TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
<add> super(null, valueTypeAdapter, instantiater);
<add> }
<add>
<add> @Override
<add> public void write(JsonWriter writer, Map<String, V> value) throws IOException {
<add> writer.beginObject();
<add> for (java.util.HashMap.Entry<String, V> entry : value.entrySet()) {
<add> writer.name(entry.getKey());
<add> valueTypeAdapter.write(writer, entry.getValue());
<add> }
<add> writer.endObject();
<add> }
<add>
<add> @Override
<add> public Map<String, V> read(JsonReader reader) throws IOException {
<add> if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
<add> reader.nextNull();
<add> return null;
<add> }
<add> if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.skipValue();
<add> return null;
<add> }
<add> reader.beginObject();
<add>
<add> Map<String, V> object = new LinkedHashMap<>();
<add> if (instantiater != null) {
<add> object = instantiater.instantiate();
<add> }
<add>
<add> while (reader.hasNext()) {
<add> com.google.gson.stream.JsonToken jsonToken = reader.peek();
<add> if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
<add> reader.skipValue();
<add> continue;
<add> }
<add>
<add> if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.beginObject();
<add> while (reader.hasNext()) {
<add> com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
<add> String key = reader.nextString();
<add> V value = valueTypeAdapter.read(reader);
<add> V replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> }
<add> reader.endObject();
<add> } else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
<add> reader.beginArray();
<add> while (reader.hasNext()) {
<add> reader.beginArray();
<add> String key = reader.nextString();
<add> V value = valueTypeAdapter.read(reader);
<add> V replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> reader.endArray();
<add> }
<add> reader.endArray();
<add> } else {
<add> reader.skipValue();
<add> }
<add> }
<add>
<add> reader.endObject();
<add> return object;
<add> }
<add> }
<add>
<add> public static class MapTypeAdapter<K, V> extends TypeAdapter<Map<K, V>> {
<add>
<add> protected Instantiater<Map> instantiater;
<add> protected TypeAdapter<V> valueTypeAdapter;
<add> private TypeAdapter<K> keyTypeAdapter;
<add>
<add> MapTypeAdapter(TypeAdapter<K> keyTypeAdapter, TypeAdapter<V> valueTypeAdapter, Instantiater<Map> instantiater) {
<add> this.keyTypeAdapter = keyTypeAdapter;
<add> this.valueTypeAdapter = valueTypeAdapter;
<add> this.instantiater = instantiater;
<add> }
<add>
<add> @Override
<add> public void write(JsonWriter writer, Map<K, V> value) throws IOException {
<add> boolean hasComplexKeys = false;
<add> List<JsonElement> keys = new ArrayList<JsonElement>(value.size());
<add>
<add> List<V> values = new ArrayList<>(value.size());
<add> for (Map.Entry<K, V> entry : value.entrySet()) {
<add> JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
<add> keys.add(keyElement);
<add> values.add(entry.getValue());
<add> hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject();
<add> }
<add>
<add> if (hasComplexKeys) {
<add> writer.beginArray();
<add> for (int i = 0; i < keys.size(); i++) {
<add> writer.beginArray(); // entry array
<add> Streams.write(keys.get(i), writer);
<add> valueTypeAdapter.write(writer, values.get(i));
<add> writer.endArray();
<add> }
<add> writer.endArray();
<add> } else {
<add> writer.beginObject();
<add> for (int i = 0; i < keys.size(); i++) {
<add> JsonElement keyElement = keys.get(i);
<add> writer.name(keyToString(keyElement));
<add> valueTypeAdapter.write(writer, values.get(i));
<add> }
<add> writer.endObject();
<add> }
<add> }
<add>
<add> @Override
<add> public Map<K, V> read(JsonReader reader) throws IOException {
<add> if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
<add> reader.nextNull();
<add> return null;
<add> }
<add> if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.skipValue();
<add> return null;
<add> }
<add> reader.beginObject();
<add>
<add> Map<K, V> object = new LinkedHashMap<>();
<add> if (instantiater != null) {
<add> object = instantiater.instantiate();
<add> }
<add>
<add> while (reader.hasNext()) {
<add> com.google.gson.stream.JsonToken jsonToken = reader.peek();
<add> if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
<add> reader.skipValue();
<add> continue;
<add> }
<add>
<add> if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.beginObject();
<add> while (reader.hasNext()) {
<add> com.google.gson.internal.JsonReaderInternalAccess.INSTANCE.promoteNameToValue(reader);
<add> K key = keyTypeAdapter.read(reader);
<add> V value = valueTypeAdapter.read(reader);
<add> V replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> }
<add> reader.endObject();
<add> } else if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
<add> reader.beginArray();
<add> while (reader.hasNext()) {
<add> reader.beginArray();
<add> K key = keyTypeAdapter.read(reader);
<add> V value = valueTypeAdapter.read(reader);
<add> V replaced = object.put(key, value);
<add> if (replaced != null) {
<add> throw new com.google.gson.JsonSyntaxException("duplicate key: " + key);
<add> }
<add> reader.endArray();
<add> }
<add> reader.endArray();
<add> } else {
<add> reader.skipValue();
<add> }
<add> }
<add>
<add> reader.endObject();
<add> return object;
<add> }
<add>
<add> private String keyToString(JsonElement keyElement) {
<add> if (keyElement.isJsonPrimitive()) {
<add> JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
<add> if (primitive.isNumber()) {
<add> return String.valueOf(primitive.getAsNumber());
<add> } else if (primitive.isBoolean()) {
<add> return Boolean.toString(primitive.getAsBoolean());
<add> } else if (primitive.isString()) {
<add> return primitive.getAsString();
<add> } else {
<add> throw new AssertionError();
<add> }
<add> } else if (keyElement.isJsonNull()) {
<add> return "null";
<add> } else {
<add> throw new AssertionError();
<add> }
<add> }
<add> }
<add>
<add> public static class ListTypeAdapter<T> extends TypeAdapter<List<T>> {
<add>
<add> private TypeAdapter<T> valueTypeAdapter;
<add> private Instantiater<List> instantiater;
<add>
<add> public ListTypeAdapter(TypeAdapter<T> valueTypeAdapter, Instantiater<List> instantiater) {
<add> this.valueTypeAdapter = valueTypeAdapter;
<add> this.instantiater = instantiater;
<add> }
<add>
<add> @Override
<add> public void write(JsonWriter writer, List<T> value) throws IOException {
<add> writer.beginArray();
<add> for (T item : value) {
<add> valueTypeAdapter.write(writer, item);
<add> }
<add> writer.endArray();
<add> }
<add>
<add> @Override
<add> public List<T> read(JsonReader reader) throws IOException {
<add> if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
<add> reader.nextNull();
<add> return null;
<add> }
<add> if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
<add> reader.skipValue();
<add> return null;
<add> }
<add> reader.beginObject();
<add>
<add> List<T> object = new ArrayList<>();
<add> if (instantiater != null) {
<add> object = instantiater.instantiate();
<add> }
<add>
<add> while (reader.hasNext()) {
<add> com.google.gson.stream.JsonToken jsonToken = reader.peek();
<add> if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
<add> reader.skipValue();
<add> continue;
<add> }
<add>
<add> if (jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) {
<add> reader.beginArray();
<add> while (reader.hasNext()) {
<add> object.add(valueTypeAdapter.read(reader));
<add> }
<add> reader.endArray();
<add> } else {
<add> reader.skipValue();
<add> }
<add> }
<add>
<add> reader.endObject();
<add> return object;
<add> }
<add> }
<add>} |
|
JavaScript | apache-2.0 | ab04a3ffcbb541266509f14736d482eb9d000bc1 | 0 | subscriptions-project/swg-js,subscriptions-project/swg-js,subscriptions-project/swg-js | /**
* Copyright 2021 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AnalyticsEvent, EventOriginator} from '../proto/api_messages';
import {AudienceActionFlow} from './audience-action-flow';
import {AutoPromptType} from '../api/basic-subscriptions';
import {ExperimentFlags} from './experiment-flags';
import {GoogleAnalyticsEventListener} from './google-analytics-event-listener';
import {MiniPromptApi} from './mini-prompt-api';
import {assert} from '../utils/log';
import {isExperimentOn} from './experiments';
const STORAGE_KEY_IMPRESSIONS = 'autopromptimp';
const STORAGE_KEY_DISMISSALS = 'autopromptdismiss';
const STORAGE_KEY_DISMISSED_PROMPTS = 'dismissedprompts';
const STORAGE_KEY_SURVEY_COMPLETED = 'surveycompleted';
const STORAGE_KEY_EVENT_SURVEY_DATA_TRANSFER_FAILED =
'surveydatatransferfailed';
const TYPE_REWARDED_SURVEY = 'TYPE_REWARDED_SURVEY';
const SECOND_IN_MILLIS = 1000;
/** @const {!Array<!AnalyticsEvent>} */
const impressionEvents = [
AnalyticsEvent.IMPRESSION_SWG_CONTRIBUTION_MINI_PROMPT,
AnalyticsEvent.IMPRESSION_SWG_SUBSCRIPTION_MINI_PROMPT,
AnalyticsEvent.IMPRESSION_OFFERS,
AnalyticsEvent.IMPRESSION_CONTRIBUTION_OFFERS,
];
/** @const {!Array<!AnalyticsEvent>} */
const dismissEvents = [
AnalyticsEvent.ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLOSE,
AnalyticsEvent.ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLOSE,
AnalyticsEvent.ACTION_CONTRIBUTION_OFFERS_CLOSED,
AnalyticsEvent.ACTION_SUBSCRIPTION_OFFERS_CLOSED,
];
/** @const {Map<AnalyticsEvent, string>} */
const COMPLETED_ACTION_TO_STORAGE_KEY_MAP = new Map([
[AnalyticsEvent.ACTION_SURVEY_DATA_TRANSFER, STORAGE_KEY_SURVEY_COMPLETED],
]);
/**
* Manages the display of subscription/contribution prompts automatically
* displayed to the user.
*/
export class AutoPromptManager {
/**
* @param {!./deps.DepsDef} deps
*/
constructor(deps) {
/** @private @const {!./deps.DepsDef} */
this.deps_ = deps;
/** @private @const {!../model/doc.Doc} */
this.doc_ = deps.doc();
/** @private @const {!../model/page-config.PageConfig} */
this.pageConfig_ = deps.pageConfig();
/** @private @const {!./entitlements-manager.EntitlementsManager} */
this.entitlementsManager_ = deps.entitlementsManager();
/** @private @const {?./client-config-manager.ClientConfigManager} */
this.clientConfigManager_ = deps.clientConfigManager();
assert(
this.clientConfigManager_,
'AutoPromptManager requires an instance of ClientConfigManager.'
);
/** @private @const {!./storage.Storage} */
this.storage_ = deps.storage();
this.deps_
.eventManager()
.registerEventListener(this.handleClientEvent_.bind(this));
/** @private @const {!MiniPromptApi} */
this.miniPromptAPI_ = this.getMiniPromptApi(deps);
this.miniPromptAPI_.init();
/** @private {boolean} */
this.autoPromptDisplayed_ = false;
/** @private {boolean} */
this.hasStoredImpression = false;
/** @private {?AudienceActionFlow} */
this.lastAudienceActionFlow_ = null;
/** @private {?string} */
this.promptDisplayed_ = null;
/** @private @const {!./client-event-manager.ClientEventManager} */
this.eventManager_ = deps.eventManager();
}
/**
* Returns an instance of MiniPromptApi. Can be overwridden by subclasses,
* such as in order to instantiate a different implementation of
* MiniPromptApi.
* @param {!./deps.DepsDef} deps
* @return {!MiniPromptApi}
* @protected
*/
getMiniPromptApi(deps) {
return new MiniPromptApi(deps);
}
/**
* Triggers the display of the auto prompt, if preconditions are met.
* Preconditions are as follows:
* - alwaysShow == true, used for demo purposes, OR
* - There is no active entitlement found AND
* - The user had not reached the maximum impressions allowed, as specified
* by the publisher
* A prompt may not be displayed if the appropriate criteria are not met.
* @param {{
* autoPromptType: (AutoPromptType|undefined),
* alwaysShow: (boolean|undefined),
* displayLargePromptFn: (function()|undefined),
* }} params
* @return {!Promise}
*/
showAutoPrompt(params) {
// Manual override of display rules, mainly for demo purposes.
if (params.alwaysShow) {
this.showPrompt_(
this.getPromptTypeToDisplay_(params.autoPromptType),
params.displayLargePromptFn
);
return Promise.resolve();
}
// Fetch entitlements and the client config from the server, so that we have
// the information we need to determine whether and which prompt should be
// displayed.
return Promise.all([
this.clientConfigManager_.getClientConfig(),
this.entitlementsManager_.getEntitlements(),
this.entitlementsManager_.getArticle(),
this.storage_.get(
STORAGE_KEY_DISMISSED_PROMPTS,
/* useLocalStorage */ true
),
]).then(([clientConfig, entitlements, article, dismissedPrompts]) => {
this.showAutoPrompt_(
clientConfig,
entitlements,
article,
dismissedPrompts,
params
);
});
}
/**
* Displays the appropriate auto prompt, depending on the fetched prompt
* configuration, entitlement state, and options specified in params.
* @param {!../model/client-config.ClientConfig|undefined} clientConfig
* @param {!../api/entitlements.Entitlements} entitlements
* @param {?./entitlements-manager.Article} article
* @param {?string|undefined} dismissedPrompts
* @param {{
* autoPromptType: (AutoPromptType|undefined),
* alwaysShow: (boolean|undefined),
* displayLargePromptFn: (function()|undefined),
* }} params
* @return {!Promise}
*/
showAutoPrompt_(
clientConfig,
entitlements,
article,
dismissedPrompts,
params
) {
return this.shouldShowAutoPrompt_(
clientConfig,
entitlements,
params.autoPromptType
)
.then((shouldShowAutoPrompt) =>
Promise.all([
this.getAudienceActionPromptType_({
article,
autoPromptType: params.autoPromptType,
dismissedPrompts,
shouldShowAutoPrompt,
}),
shouldShowAutoPrompt,
])
)
.then(([potentialActionPromptType, shouldShowAutoPrompt]) => {
const promptFn = potentialActionPromptType
? this.audienceActionPrompt_({
action: potentialActionPromptType,
autoPromptType: params.autoPromptType,
})
: params.displayLargePromptFn;
if (!shouldShowAutoPrompt) {
if (
this.shouldShowBlockingPrompt_(
entitlements,
/* hasPotentialAudienceAction */ !!potentialActionPromptType
) &&
promptFn
) {
promptFn();
}
return;
}
this.deps_.win().setTimeout(() => {
this.autoPromptDisplayed_ = true;
this.showPrompt_(
this.getPromptTypeToDisplay_(params.autoPromptType),
promptFn
);
}, (clientConfig?.autoPromptConfig.clientDisplayTrigger.displayDelaySeconds || 0) * SECOND_IN_MILLIS);
});
}
/**
* Determines whether a mini prompt for contributions or subscriptions should
* be shown.
* @param {!../model/client-config.ClientConfig|undefined} clientConfig
* @param {!../api/entitlements.Entitlements} entitlements
* @param {!AutoPromptType|undefined} autoPromptType
* @returns {!Promise<boolean>}
*/
shouldShowAutoPrompt_(clientConfig, entitlements, autoPromptType) {
// If false publication predicate was returned in the response, don't show
// the prompt.
if (
clientConfig.uiPredicates &&
!clientConfig.uiPredicates.canDisplayAutoPrompt
) {
return Promise.resolve(false);
}
// If the auto prompt type is not supported, don't show the prompt.
if (
autoPromptType === undefined ||
autoPromptType === AutoPromptType.NONE
) {
return Promise.resolve(false);
}
// If we found a valid entitlement, don't show the prompt.
if (entitlements.enablesThis()) {
return Promise.resolve(false);
}
// The auto prompt is only for non-paygated content.
if (this.pageConfig_.isLocked()) {
return Promise.resolve(false);
}
// Don't cap subscription prompts.
if (
autoPromptType === AutoPromptType.SUBSCRIPTION ||
autoPromptType === AutoPromptType.SUBSCRIPTION_LARGE
) {
return Promise.resolve(true);
}
// If no auto prompt config was returned in the response, don't show
// the prompt.
let autoPromptConfig = undefined;
if (
clientConfig === undefined ||
clientConfig.autoPromptConfig === undefined
) {
return Promise.resolve(false);
} else {
autoPromptConfig = clientConfig.autoPromptConfig;
}
// Fetched config returned no maximum cap.
if (autoPromptConfig.impressionConfig.maxImpressions === undefined) {
return Promise.resolve(true);
}
// See if we should display the auto prompt based on the config and logged
// events.
return Promise.all([this.getImpressions_(), this.getDismissals_()]).then(
(values) => {
const impressions = values[0];
const dismissals = values[1];
const lastImpression = impressions[impressions.length - 1];
const lastDismissal = dismissals[dismissals.length - 1];
// If the user has reached the maxDismissalsPerWeek, and
// maxDismissalsResultingHideSeconds has not yet passed, don't show the
// prompt.
if (
autoPromptConfig.explicitDismissalConfig.maxDismissalsPerWeek &&
dismissals.length >=
autoPromptConfig.explicitDismissalConfig.maxDismissalsPerWeek &&
Date.now() - lastDismissal <
(autoPromptConfig.explicitDismissalConfig
.maxDismissalsResultingHideSeconds || 0) *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has previously dismissed the prompt, and backOffSeconds has
// not yet passed, don't show the prompt.
if (
autoPromptConfig.explicitDismissalConfig.backOffSeconds &&
dismissals.length > 0 &&
Date.now() - lastDismissal <
autoPromptConfig.explicitDismissalConfig.backOffSeconds *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has reached the maxImpressions, and
// maxImpressionsResultingHideSeconds has not yet passed, don't show the
// prompt.
if (
autoPromptConfig.impressionConfig.maxImpressions &&
impressions.length >=
autoPromptConfig.impressionConfig.maxImpressions &&
Date.now() - lastImpression <
(autoPromptConfig.impressionConfig
.maxImpressionsResultingHideSeconds || 0) *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has seen the prompt, and backOffSeconds has
// not yet passed, don't show the prompt. This is to prevent the prompt
// from showing in consecutive visits.
if (
autoPromptConfig.impressionConfig.backOffSeconds &&
impressions.length > 0 &&
Date.now() - lastImpression <
autoPromptConfig.impressionConfig.backOffSeconds * SECOND_IN_MILLIS
) {
return false;
}
return true;
}
);
}
/**
* Determines what Audience Action prompt should be shown.
*
* In the case of Subscription models, we always show the first available prompt.
*
* In the case of Contribution models, we only show non-previously dismissed actions
* after the initial Contribution prompt. We also always default to showing the Contribution
* prompt if the reader is currently inside of the frequency window, indicated by shouldShowAutoPrompt.
* @param {{
* article: (?./entitlements-manager.Article|undefined),
* autoPromptType: (AutoPromptType|undefined),
* dismissedPrompts: (?string|undefined),
* shouldShowAutoPrompt: (boolean|undefined),
* }} params
* @return {!Promise<string|undefined>}
*/
getAudienceActionPromptType_({
article,
autoPromptType,
dismissedPrompts,
shouldShowAutoPrompt,
}) {
const audienceActions = article?.audienceActions?.actions || [];
// Count completed surveys.
return Promise.all([
this.storage_.getEvent(
COMPLETED_ACTION_TO_STORAGE_KEY_MAP.get(
AnalyticsEvent.ACTION_SURVEY_DATA_TRANSFER
)
),
this.storage_.getEvent(STORAGE_KEY_EVENT_SURVEY_DATA_TRANSFER_FAILED),
]).then(
([surveyCompletionTimestamps, surveyDataTransferFailureTimestamps]) => {
const hasCompletedSurveys = surveyCompletionTimestamps.length >= 1;
const hasRecentSurveyDataTransferFailure =
surveyDataTransferFailureTimestamps.length >= 1;
const isSurveyEligible =
!hasCompletedSurveys && !hasRecentSurveyDataTransferFailure;
let potentialActions = audienceActions.filter((action) =>
this.checkActionEligibility_(action.type, isSurveyEligible)
);
// No audience actions means use the default prompt.
if (potentialActions.length === 0) {
return undefined;
}
// Default to the first recommended action.
let actionToUse = potentialActions[0].type;
// Contribution prompts should appear before recommended actions, so we'll need
// to check if we have shown it before.
if (
autoPromptType === AutoPromptType.CONTRIBUTION ||
autoPromptType === AutoPromptType.CONTRIBUTION_LARGE
) {
if (!dismissedPrompts) {
this.promptDisplayed_ = AutoPromptType.CONTRIBUTION;
return undefined;
}
const previousPrompts = dismissedPrompts.split(',');
potentialActions = potentialActions.filter(
(action) => !previousPrompts.includes(action.type)
);
// If all actions have been dismissed or the frequency indicates that we
// should show the Contribution prompt again regardless of previous dismissals,
// we don't want to record the Contribution dismissal
if (potentialActions.length === 0 || shouldShowAutoPrompt) {
return undefined;
}
// Otherwise, set to the next recommended action. If the last dismissal was the
// Contribution prompt, this will resolve to the first recommended action.
actionToUse = potentialActions[0].type;
this.promptDisplayed_ = actionToUse;
}
return actionToUse;
}
);
}
/**
* @param {{
* action: (string|undefined),
* autoPromptType: (AutoPromptType|undefined)
* }} params
* @return {!function()}
*/
audienceActionPrompt_({action, autoPromptType}) {
return () => {
const params = {
action,
autoPromptType,
onCancel: () => this.storeLastDismissal_(),
};
const lastAudienceActionFlow = new AudienceActionFlow(this.deps_, params);
this.setLastAudienceActionFlow(lastAudienceActionFlow);
lastAudienceActionFlow.start();
};
}
/** @param {!AudienceActionFlow} flow */
setLastAudienceActionFlow(flow) {
this.lastAudienceActionFlow_ = flow;
}
/** @return {?AudienceActionFlow} */
getLastAudienceActionFlow() {
return this.lastAudienceActionFlow_;
}
/**
* Shows the prompt based on the type specified.
* @param {AutoPromptType|undefined} autoPromptType
* @param {function()|undefined} displayLargePromptFn
* @returns
*/
showPrompt_(autoPromptType, displayLargePromptFn) {
if (
autoPromptType === AutoPromptType.SUBSCRIPTION ||
autoPromptType === AutoPromptType.CONTRIBUTION
) {
this.miniPromptAPI_.create({
autoPromptType,
clickCallback: displayLargePromptFn,
});
} else if (
(autoPromptType === AutoPromptType.SUBSCRIPTION_LARGE ||
autoPromptType === AutoPromptType.CONTRIBUTION_LARGE) &&
displayLargePromptFn
) {
displayLargePromptFn();
}
}
/**
* Returns which type of prompt to display based on the type specified,
* the viewport width, and whether the disableDesktopMiniprompt experiment
* is enabled.
*
* If the disableDesktopMiniprompt experiment is enabled and the desktop is
* wider than 480px then the large prompt type will be substituted for the mini
* prompt. The original promptType will be returned as-is in all other cases.
* @param {AutoPromptType|undefined} promptType
* @returns
*/
getPromptTypeToDisplay_(promptType) {
const disableDesktopMiniprompt = isExperimentOn(
this.doc_.getWin(),
ExperimentFlags.DISABLE_DESKTOP_MINIPROMPT
);
const isWideDesktop = this.doc_.getWin()./* OK */ innerWidth > 480;
if (disableDesktopMiniprompt && isWideDesktop) {
if (promptType === AutoPromptType.SUBSCRIPTION) {
this.logDisableMinipromptEvent_(promptType);
return AutoPromptType.SUBSCRIPTION_LARGE;
}
if (promptType === AutoPromptType.CONTRIBUTION) {
this.logDisableMinipromptEvent_(promptType);
return AutoPromptType.CONTRIBUTION_LARGE;
}
}
return promptType;
}
/**
* Logs the disable miniprompt event.
* @param {AutoPromptType|undefined} overriddenPromptType
*/
logDisableMinipromptEvent_(overriddenPromptType) {
this.eventManager_.logEvent({
eventType: AnalyticsEvent.EVENT_DISABLE_MINIPROMPT_DESKTOP,
eventOriginator: EventOriginator.SWG_CLIENT,
isFromUserAction: false,
additionalParameters: {
publicationid: this.pageConfig_.getPublicationId(),
promptType: overriddenPromptType,
},
});
}
/**
* Determines whether a larger, blocking prompt should be shown.
* @param {!../api/entitlements.Entitlements} entitlements
* @param {!boolean} hasPotentialAudienceAction
* @returns {boolean}
*/
shouldShowBlockingPrompt_(entitlements, hasPotentialAudienceAction) {
return (
(this.pageConfig_.isLocked() || hasPotentialAudienceAction) &&
!entitlements.enablesThis()
);
}
/**
* Listens for relevant prompt impression events, dismissal events, and completed
* action events, and logs them to local storage for use in determining whether
* to display the prompt in the future.
* @param {../api/client-event-manager-api.ClientEvent} event
* @return {!Promise}
*/
handleClientEvent_(event) {
// Impressions and dimissals of forced (for paygated) or manually triggered
// prompts do not count toward the frequency caps.
if (
!this.autoPromptDisplayed_ ||
this.pageConfig_.isLocked() ||
!event.eventType
) {
return Promise.resolve();
}
// Prompt impression should be stored if no previous one has been stored.
// This is to prevent the case that user clicks the mini prompt, and both
// impressions of the mini and large prompts would be counted towards the
// cap.
if (
!this.hasStoredImpression &&
impressionEvents.includes(event.eventType)
) {
this.hasStoredImpression = true;
return this.storage_.storeEvent(STORAGE_KEY_IMPRESSIONS);
}
if (dismissEvents.includes(event.eventType)) {
return Promise.all([
this.storage_.storeEvent(STORAGE_KEY_DISMISSALS),
// If we need to keep track of the prompt that was dismissed, make sure to
// record it.
this.storeLastDismissal_(),
]);
}
if (COMPLETED_ACTION_TO_STORAGE_KEY_MAP.has(event.eventType)) {
return this.storage_.storeEvent(
COMPLETED_ACTION_TO_STORAGE_KEY_MAP.get(event.eventType)
);
}
return Promise.resolve();
}
/**
* Adds the current prompt displayed to the array of all dismissed prompts.
* @returns {!Promise}
*/
storeLastDismissal_() {
return this.promptDisplayed_
? this.storage_
.get(STORAGE_KEY_DISMISSED_PROMPTS, /* useLocalStorage */ true)
.then((value) => {
const prompt = /** @type {string} */ (this.promptDisplayed_);
this.storage_.set(
STORAGE_KEY_DISMISSED_PROMPTS,
value ? value + ',' + prompt : prompt,
/* useLocalStorage */ true
);
})
: Promise.resolve();
}
/**
* Retrieves the locally stored impressions of the auto prompt, within a week
* of the current time.
* @return {!Promise<!Array<number>>}
*/
getImpressions_() {
return this.storage_.getEvent(STORAGE_KEY_IMPRESSIONS);
}
/**
* Retrieves the locally stored dismissals of the auto prompt, within a week
* of the current time.
* @return {!Promise<!Array<number>>}
*/
getDismissals_() {
return this.storage_.getEvent(STORAGE_KEY_DISMISSALS);
}
/**
* Checks AudienceAction eligbility, used to filter potential actions.
* @param {string} actionType
* @param {boolean} isSurveyEligible
* @return {boolean}
*/
checkActionEligibility_(actionType, isSurveyEligible) {
if (actionType === TYPE_REWARDED_SURVEY) {
const isAnalyticsEligible =
GoogleAnalyticsEventListener.isGaEligible(this.deps_) ||
GoogleAnalyticsEventListener.isGtagEligible(this.deps_);
return isSurveyEligible && isAnalyticsEligible;
}
return true;
}
}
| src/runtime/auto-prompt-manager.js | /**
* Copyright 2021 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AnalyticsEvent, EventOriginator} from '../proto/api_messages';
import {AudienceActionFlow} from './audience-action-flow';
import {AutoPromptType} from '../api/basic-subscriptions';
import {ExperimentFlags} from './experiment-flags';
import {GoogleAnalyticsEventListener} from './google-analytics-event-listener';
import {MiniPromptApi} from './mini-prompt-api';
import {assert} from '../utils/log';
import {isExperimentOn} from './experiments';
const STORAGE_KEY_IMPRESSIONS = 'autopromptimp';
const STORAGE_KEY_DISMISSALS = 'autopromptdismiss';
const STORAGE_KEY_DISMISSED_PROMPTS = 'dismissedprompts';
const STORAGE_KEY_SURVEY_COMPLETED = 'surveycompleted';
const STORAGE_KEY_EVENT_SURVEY_DATA_TRANSFER_FAILED =
'surveydatatransferfailed';
const TYPE_REWARDED_SURVEY = 'TYPE_REWARDED_SURVEY';
const SECOND_IN_MILLIS = 1000;
/** @const {!Array<!AnalyticsEvent>} */
const impressionEvents = [
AnalyticsEvent.IMPRESSION_SWG_CONTRIBUTION_MINI_PROMPT,
AnalyticsEvent.IMPRESSION_SWG_SUBSCRIPTION_MINI_PROMPT,
AnalyticsEvent.IMPRESSION_OFFERS,
AnalyticsEvent.IMPRESSION_CONTRIBUTION_OFFERS,
];
/** @const {!Array<!AnalyticsEvent>} */
const dismissEvents = [
AnalyticsEvent.ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLOSE,
AnalyticsEvent.ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLOSE,
AnalyticsEvent.ACTION_CONTRIBUTION_OFFERS_CLOSED,
AnalyticsEvent.ACTION_SUBSCRIPTION_OFFERS_CLOSED,
];
/** @const {Map<AnalyticsEvent, string>} */
const COMPLETED_ACTION_TO_STORAGE_KEY_MAP = new Map([
[AnalyticsEvent.ACTION_SURVEY_DATA_TRANSFER, STORAGE_KEY_SURVEY_COMPLETED],
]);
/**
* Manages the display of subscription/contribution prompts automatically
* displayed to the user.
*/
export class AutoPromptManager {
/**
* @param {!./deps.DepsDef} deps
*/
constructor(deps) {
/** @private @const {!./deps.DepsDef} */
this.deps_ = deps;
/** @private @const {!../model/doc.Doc} */
this.doc_ = deps.doc();
/** @private @const {!../model/page-config.PageConfig} */
this.pageConfig_ = deps.pageConfig();
/** @private @const {!./entitlements-manager.EntitlementsManager} */
this.entitlementsManager_ = deps.entitlementsManager();
/** @private @const {?./client-config-manager.ClientConfigManager} */
this.clientConfigManager_ = deps.clientConfigManager();
assert(
this.clientConfigManager_,
'AutoPromptManager requires an instance of ClientConfigManager.'
);
/** @private @const {!./storage.Storage} */
this.storage_ = deps.storage();
this.deps_
.eventManager()
.registerEventListener(this.handleClientEvent_.bind(this));
/** @private @const {!MiniPromptApi} */
this.miniPromptAPI_ = this.getMiniPromptApi(deps);
this.miniPromptAPI_.init();
/** @private {boolean} */
this.autoPromptDisplayed_ = false;
/** @private {boolean} */
this.hasStoredImpression = false;
/** @private {?AudienceActionFlow} */
this.lastAudienceActionFlow_ = null;
/** @private {?string} */
this.promptDisplayed_ = null;
/** @private @const {!./client-event-manager.ClientEventManager} */
this.eventManager_ = deps.eventManager();
}
/**
* Returns an instance of MiniPromptApi. Can be overwridden by subclasses,
* such as in order to instantiate a different implementation of
* MiniPromptApi.
* @param {!./deps.DepsDef} deps
* @return {!MiniPromptApi}
* @protected
*/
getMiniPromptApi(deps) {
return new MiniPromptApi(deps);
}
/**
* Triggers the display of the auto prompt, if preconditions are met.
* Preconditions are as follows:
* - alwaysShow == true, used for demo purposes, OR
* - There is no active entitlement found AND
* - The user had not reached the maximum impressions allowed, as specified
* by the publisher
* A prompt may not be displayed if the appropriate criteria are not met.
* @param {{
* autoPromptType: (AutoPromptType|undefined),
* alwaysShow: (boolean|undefined),
* displayLargePromptFn: (function()|undefined),
* }} params
* @return {!Promise}
*/
showAutoPrompt(params) {
// Manual override of display rules, mainly for demo purposes.
if (params.alwaysShow) {
this.showPrompt_(
this.getPromptTypeToDisplay_(params.autoPromptType),
params.displayLargePromptFn
);
return Promise.resolve();
}
// Fetch entitlements and the client config from the server, so that we have
// the information we need to determine whether and which prompt should be
// displayed.
return Promise.all([
this.clientConfigManager_.getClientConfig(),
this.entitlementsManager_.getEntitlements(),
this.entitlementsManager_.getArticle(),
this.storage_.get(
STORAGE_KEY_DISMISSED_PROMPTS,
/* useLocalStorage */ true
),
]).then(([clientConfig, entitlements, article, dismissedPrompts]) => {
this.showAutoPrompt_(
clientConfig,
entitlements,
article,
dismissedPrompts,
params
);
});
}
/**
* Displays the appropriate auto prompt, depending on the fetched prompt
* configuration, entitlement state, and options specified in params.
* @param {!../model/client-config.ClientConfig|undefined} clientConfig
* @param {!../api/entitlements.Entitlements} entitlements
* @param {?./entitlements-manager.Article} article
* @param {?string|undefined} dismissedPrompts
* @param {{
* autoPromptType: (AutoPromptType|undefined),
* alwaysShow: (boolean|undefined),
* displayLargePromptFn: (function()|undefined),
* }} params
* @return {!Promise}
*/
showAutoPrompt_(
clientConfig,
entitlements,
article,
dismissedPrompts,
params
) {
return this.shouldShowAutoPrompt_(
clientConfig,
entitlements,
params.autoPromptType
)
.then((shouldShowAutoPrompt) =>
Promise.all([
this.getAudienceActionPromptType_({
article,
autoPromptType: params.autoPromptType,
dismissedPrompts,
shouldShowAutoPrompt,
}),
shouldShowAutoPrompt,
])
)
.then(([potentialActionPromptType, shouldShowAutoPrompt]) => {
const promptFn = potentialActionPromptType
? this.audienceActionPrompt_({
action: potentialActionPromptType,
autoPromptType: params.autoPromptType,
})
: params.displayLargePromptFn;
if (!shouldShowAutoPrompt) {
if (
this.shouldShowBlockingPrompt_(
entitlements,
/* hasPotentialAudienceAction */ !!potentialActionPromptType
) &&
promptFn
) {
promptFn();
}
return;
}
this.deps_.win().setTimeout(() => {
this.autoPromptDisplayed_ = true;
this.showPrompt_(
this.getPromptTypeToDisplay_(params.autoPromptType),
promptFn
);
}, (clientConfig?.autoPromptConfig.clientDisplayTrigger.displayDelaySeconds || 0) * SECOND_IN_MILLIS);
});
}
/**
* Determines whether a mini prompt for contributions or subscriptions should
* be shown.
* @param {!../model/client-config.ClientConfig|undefined} clientConfig
* @param {!../api/entitlements.Entitlements} entitlements
* @param {!AutoPromptType|undefined} autoPromptType
* @returns {!Promise<boolean>}
*/
shouldShowAutoPrompt_(clientConfig, entitlements, autoPromptType) {
// If false publication predicate was returned in the response, don't show
// the prompt.
if (
clientConfig.uiPredicates &&
!clientConfig.uiPredicates.canDisplayAutoPrompt
) {
return Promise.resolve(false);
}
// If the auto prompt type is not supported, don't show the prompt.
if (
autoPromptType === undefined ||
autoPromptType === AutoPromptType.NONE
) {
return Promise.resolve(false);
}
// If we found a valid entitlement, don't show the prompt.
if (entitlements.enablesThis()) {
return Promise.resolve(false);
}
// The auto prompt is only for non-paygated content.
if (this.pageConfig_.isLocked()) {
return Promise.resolve(false);
}
// Don't cap subscription prompts.
if (
autoPromptType === AutoPromptType.SUBSCRIPTION ||
autoPromptType === AutoPromptType.SUBSCRIPTION_LARGE
) {
return Promise.resolve(true);
}
// If no auto prompt config was returned in the response, don't show
// the prompt.
let autoPromptConfig = undefined;
if (
clientConfig === undefined ||
clientConfig.autoPromptConfig === undefined
) {
return Promise.resolve(false);
} else {
autoPromptConfig = clientConfig.autoPromptConfig;
}
// Fetched config returned no maximum cap.
if (autoPromptConfig.impressionConfig.maxImpressions === undefined) {
return Promise.resolve(true);
}
// See if we should display the auto prompt based on the config and logged
// events.
return Promise.all([this.getImpressions_(), this.getDismissals_()]).then(
(values) => {
const impressions = values[0];
const dismissals = values[1];
const lastImpression = impressions[impressions.length - 1];
const lastDismissal = dismissals[dismissals.length - 1];
// If the user has reached the maxDismissalsPerWeek, and
// maxDismissalsResultingHideSeconds has not yet passed, don't show the
// prompt.
if (
autoPromptConfig.explicitDismissalConfig.maxDismissalsPerWeek &&
dismissals.length >=
autoPromptConfig.explicitDismissalConfig.maxDismissalsPerWeek &&
Date.now() - lastDismissal <
(autoPromptConfig.explicitDismissalConfig
.maxDismissalsResultingHideSeconds || 0) *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has previously dismissed the prompt, and backOffSeconds has
// not yet passed, don't show the prompt.
if (
autoPromptConfig.explicitDismissalConfig.backOffSeconds &&
dismissals.length > 0 &&
Date.now() - lastDismissal <
autoPromptConfig.explicitDismissalConfig.backOffSeconds *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has reached the maxImpressions, and
// maxImpressionsResultingHideSeconds has not yet passed, don't show the
// prompt.
if (
autoPromptConfig.impressionConfig.maxImpressions &&
impressions.length >=
autoPromptConfig.impressionConfig.maxImpressions &&
Date.now() - lastImpression <
(autoPromptConfig.impressionConfig
.maxImpressionsResultingHideSeconds || 0) *
SECOND_IN_MILLIS
) {
return false;
}
// If the user has seen the prompt, and backOffSeconds has
// not yet passed, don't show the prompt. This is to prevent the prompt
// from showing in consecutive visits.
if (
autoPromptConfig.impressionConfig.backOffSeconds &&
impressions.length > 0 &&
Date.now() - lastImpression <
autoPromptConfig.impressionConfig.backOffSeconds * SECOND_IN_MILLIS
) {
return false;
}
return true;
}
);
}
/**
* Determines what Audience Action prompt should be shown.
*
* In the case of Subscription models, we always show the first available prompt.
*
* In the case of Contribution models, we only show non-previously dismissed actions
* after the initial Contribution prompt. We also always default to showing the Contribution
* prompt if the reader is currently inside of the frequency window, indicated by shouldShowAutoPrompt.
* @param {{
* article: (?./entitlements-manager.Article|undefined),
* autoPromptType: (AutoPromptType|undefined),
* dismissedPrompts: (?string|undefined),
* shouldShowAutoPrompt: (boolean|undefined),
* }} params
* @return {!Promise<string|undefined>}
*/
getAudienceActionPromptType_({
article,
autoPromptType,
dismissedPrompts,
shouldShowAutoPrompt,
}) {
const audienceActions = article?.audienceActions?.actions || [];
// Count completed surveys.
return Promise.all([
this.storage_.getEvent(
COMPLETED_ACTION_TO_STORAGE_KEY_MAP.get(
AnalyticsEvent.ACTION_SURVEY_DATA_TRANSFER
)
),
this.storage_.getEvent(STORAGE_KEY_EVENT_SURVEY_DATA_TRANSFER_FAILED),
]).then(
([surveyCompletionTimestamps, surveyDataTransferFailureTimestamps]) => {
const hasCompletedSurveys = surveyCompletionTimestamps.length >= 1;
const hasRecentSurveyDataTransferFailure =
surveyDataTransferFailureTimestamps &&
Date.now() -
surveyDataTransferFailureTimestamps[
surveyDataTransferFailureTimestamps - 1
] <
10 * 60 * SECOND_IN_MILLIS; // 10 min
const isSurveyEligible =
!hasCompletedSurveys && !hasRecentSurveyDataTransferFailure;
let potentialActions = audienceActions.filter((action) =>
this.checkActionEligibility_(action.type, isSurveyEligible)
);
// No audience actions means use the default prompt.
if (potentialActions.length === 0) {
return undefined;
}
// Default to the first recommended action.
let actionToUse = potentialActions[0].type;
// Contribution prompts should appear before recommended actions, so we'll need
// to check if we have shown it before.
if (
autoPromptType === AutoPromptType.CONTRIBUTION ||
autoPromptType === AutoPromptType.CONTRIBUTION_LARGE
) {
if (!dismissedPrompts) {
this.promptDisplayed_ = AutoPromptType.CONTRIBUTION;
return undefined;
}
const previousPrompts = dismissedPrompts.split(',');
potentialActions = potentialActions.filter(
(action) => !previousPrompts.includes(action.type)
);
// If all actions have been dismissed or the frequency indicates that we
// should show the Contribution prompt again regardless of previous dismissals,
// we don't want to record the Contribution dismissal
if (potentialActions.length === 0 || shouldShowAutoPrompt) {
return undefined;
}
// Otherwise, set to the next recommended action. If the last dismissal was the
// Contribution prompt, this will resolve to the first recommended action.
actionToUse = potentialActions[0].type;
this.promptDisplayed_ = actionToUse;
}
return actionToUse;
}
);
}
/**
* @param {{
* action: (string|undefined),
* autoPromptType: (AutoPromptType|undefined)
* }} params
* @return {!function()}
*/
audienceActionPrompt_({action, autoPromptType}) {
return () => {
const params = {
action,
autoPromptType,
onCancel: () => this.storeLastDismissal_(),
};
const lastAudienceActionFlow = new AudienceActionFlow(this.deps_, params);
this.setLastAudienceActionFlow(lastAudienceActionFlow);
lastAudienceActionFlow.start();
};
}
/** @param {!AudienceActionFlow} flow */
setLastAudienceActionFlow(flow) {
this.lastAudienceActionFlow_ = flow;
}
/** @return {?AudienceActionFlow} */
getLastAudienceActionFlow() {
return this.lastAudienceActionFlow_;
}
/**
* Shows the prompt based on the type specified.
* @param {AutoPromptType|undefined} autoPromptType
* @param {function()|undefined} displayLargePromptFn
* @returns
*/
showPrompt_(autoPromptType, displayLargePromptFn) {
if (
autoPromptType === AutoPromptType.SUBSCRIPTION ||
autoPromptType === AutoPromptType.CONTRIBUTION
) {
this.miniPromptAPI_.create({
autoPromptType,
clickCallback: displayLargePromptFn,
});
} else if (
(autoPromptType === AutoPromptType.SUBSCRIPTION_LARGE ||
autoPromptType === AutoPromptType.CONTRIBUTION_LARGE) &&
displayLargePromptFn
) {
displayLargePromptFn();
}
}
/**
* Returns which type of prompt to display based on the type specified,
* the viewport width, and whether the disableDesktopMiniprompt experiment
* is enabled.
*
* If the disableDesktopMiniprompt experiment is enabled and the desktop is
* wider than 480px then the large prompt type will be substituted for the mini
* prompt. The original promptType will be returned as-is in all other cases.
* @param {AutoPromptType|undefined} promptType
* @returns
*/
getPromptTypeToDisplay_(promptType) {
const disableDesktopMiniprompt = isExperimentOn(
this.doc_.getWin(),
ExperimentFlags.DISABLE_DESKTOP_MINIPROMPT
);
const isWideDesktop = this.doc_.getWin()./* OK */ innerWidth > 480;
if (disableDesktopMiniprompt && isWideDesktop) {
if (promptType === AutoPromptType.SUBSCRIPTION) {
this.logDisableMinipromptEvent_(promptType);
return AutoPromptType.SUBSCRIPTION_LARGE;
}
if (promptType === AutoPromptType.CONTRIBUTION) {
this.logDisableMinipromptEvent_(promptType);
return AutoPromptType.CONTRIBUTION_LARGE;
}
}
return promptType;
}
/**
* Logs the disable miniprompt event.
* @param {AutoPromptType|undefined} overriddenPromptType
*/
logDisableMinipromptEvent_(overriddenPromptType) {
this.eventManager_.logEvent({
eventType: AnalyticsEvent.EVENT_DISABLE_MINIPROMPT_DESKTOP,
eventOriginator: EventOriginator.SWG_CLIENT,
isFromUserAction: false,
additionalParameters: {
publicationid: this.pageConfig_.getPublicationId(),
promptType: overriddenPromptType,
},
});
}
/**
* Determines whether a larger, blocking prompt should be shown.
* @param {!../api/entitlements.Entitlements} entitlements
* @param {!boolean} hasPotentialAudienceAction
* @returns {boolean}
*/
shouldShowBlockingPrompt_(entitlements, hasPotentialAudienceAction) {
return (
(this.pageConfig_.isLocked() || hasPotentialAudienceAction) &&
!entitlements.enablesThis()
);
}
/**
* Listens for relevant prompt impression events, dismissal events, and completed
* action events, and logs them to local storage for use in determining whether
* to display the prompt in the future.
* @param {../api/client-event-manager-api.ClientEvent} event
* @return {!Promise}
*/
handleClientEvent_(event) {
// Impressions and dimissals of forced (for paygated) or manually triggered
// prompts do not count toward the frequency caps.
if (
!this.autoPromptDisplayed_ ||
this.pageConfig_.isLocked() ||
!event.eventType
) {
return Promise.resolve();
}
// Prompt impression should be stored if no previous one has been stored.
// This is to prevent the case that user clicks the mini prompt, and both
// impressions of the mini and large prompts would be counted towards the
// cap.
if (
!this.hasStoredImpression &&
impressionEvents.includes(event.eventType)
) {
this.hasStoredImpression = true;
return this.storage_.storeEvent(STORAGE_KEY_IMPRESSIONS);
}
if (dismissEvents.includes(event.eventType)) {
return Promise.all([
this.storage_.storeEvent(STORAGE_KEY_DISMISSALS),
// If we need to keep track of the prompt that was dismissed, make sure to
// record it.
this.storeLastDismissal_(),
]);
}
if (COMPLETED_ACTION_TO_STORAGE_KEY_MAP.has(event.eventType)) {
return this.storage_.storeEvent(
COMPLETED_ACTION_TO_STORAGE_KEY_MAP.get(event.eventType)
);
}
return Promise.resolve();
}
/**
* Adds the current prompt displayed to the array of all dismissed prompts.
* @returns {!Promise}
*/
storeLastDismissal_() {
return this.promptDisplayed_
? this.storage_
.get(STORAGE_KEY_DISMISSED_PROMPTS, /* useLocalStorage */ true)
.then((value) => {
const prompt = /** @type {string} */ (this.promptDisplayed_);
this.storage_.set(
STORAGE_KEY_DISMISSED_PROMPTS,
value ? value + ',' + prompt : prompt,
/* useLocalStorage */ true
);
})
: Promise.resolve();
}
/**
* Retrieves the locally stored impressions of the auto prompt, within a week
* of the current time.
* @return {!Promise<!Array<number>>}
*/
getImpressions_() {
return this.storage_.getEvent(STORAGE_KEY_IMPRESSIONS);
}
/**
* Retrieves the locally stored dismissals of the auto prompt, within a week
* of the current time.
* @return {!Promise<!Array<number>>}
*/
getDismissals_() {
return this.storage_.getEvent(STORAGE_KEY_DISMISSALS);
}
/**
* Checks AudienceAction eligbility, used to filter potential actions.
* @param {string} actionType
* @param {boolean} isSurveyEligible
* @return {boolean}
*/
checkActionEligibility_(actionType, isSurveyEligible) {
if (actionType === TYPE_REWARDED_SURVEY) {
const isAnalyticsEligible =
GoogleAnalyticsEventListener.isGaEligible(this.deps_) ||
GoogleAnalyticsEventListener.isGtagEligible(this.deps_);
return isSurveyEligible && isAnalyticsEligible;
}
return true;
}
}
| remove time requirement on survey fail
| src/runtime/auto-prompt-manager.js | remove time requirement on survey fail | <ide><path>rc/runtime/auto-prompt-manager.js
<ide> ([surveyCompletionTimestamps, surveyDataTransferFailureTimestamps]) => {
<ide> const hasCompletedSurveys = surveyCompletionTimestamps.length >= 1;
<ide> const hasRecentSurveyDataTransferFailure =
<del> surveyDataTransferFailureTimestamps &&
<del> Date.now() -
<del> surveyDataTransferFailureTimestamps[
<del> surveyDataTransferFailureTimestamps - 1
<del> ] <
<del> 10 * 60 * SECOND_IN_MILLIS; // 10 min
<add> surveyDataTransferFailureTimestamps.length >= 1;
<ide> const isSurveyEligible =
<ide> !hasCompletedSurveys && !hasRecentSurveyDataTransferFailure;
<ide> |
|
JavaScript | apache-2.0 | c76756e4f5361de991a41192897c5b3af6c56b29 | 0 | FundacionZamoraTeran/Orthography,FundacionZamoraTeran/Orthography,FundacionZamoraTeran/Orthography | define(function (require) {
var jquery = require("jquery");
var activity = require("sugar-web/activity/activity");
var palette = require("sugar-web/graphics/palette");
var icon = require("sugar-web/graphics/icon");
var dictstore = require("sugar-web/dictstore")
var l10n = require("webL10n");
var spritely = require("spritely");
var words = null;
function count(array) {
var counter = 0;
for (var i = 0; i < array.length; i++) {
if (array[i]) {
counter++;
}
}
return counter;
}
function getWords(level) {
if (words == null) {
words = require("words");
}
return words[level][Math.floor(Math.random() * (words[level].length))];
}
function Game() {
this.level = null;
this.mode = null;
this.currentWord = [];
this.answer = '';
this.boxGame = null;
this.sentence = null;
this.answerBox = null;
this.error_count = 0;
this.point_count = 0;
this.win_level = 0;
this.character = 0;
this.data_level = Array(12);
function onStoreReady() {
if (localStorage['level']) {
this.data_level = JSON.parse(localStorage['level']);
console.log(this.data_level);
for (var i = 1; i <= this.data_level.length; i++) {
if (this.data_level[i - 1]) {
document.getElementById(String(i)).className = 'world world-'+ i +' done';
}
}
}
}
dictstore.init(onStoreReady);
this.init = function(level, mode) {
this.level = level;
this.mode = mode;
this.point_count = 0;
if (this.mode == '1') {
this.win_level = 70;
}
else if (this.mode == '2') {
this.win_level = 40;
}
document.getElementById('point-bar').innerHTML = '';
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
/*
I didn't expect to use JQuery at the beginning, but it's required
by the animation library.
I hope you love spaguetti code.
*/
$('#land').css('background', 'url(../images/land-' + level + '.png) left top repeat-x');
$('#land').pan({fps: 30, speed: 0.7, dir: 'left'});
$('#land').spStart();
console.log('Iniciar animacion');
if (this.character == 1) {
document.getElementById('walking-character').className = 'boy-' + level;
}
else {
document.getElementById('walking-character').className = 'girl-' + level;
}
this.interface();
}
this.start = function() {
this.currentWord = getWords(this.level);
this.answer = this.currentWord['answer'];
sentence.innerHTML = this.currentWord['sentence'];
if (sentence.className == 'main-sentence') {
sentence.className = '';
}
if (this.mode == '1') {
document.getElementById('op1').innerHTML = this.currentWord['op1'];
document.getElementById('op2').innerHTML = this.currentWord['op2'];
}
}
this.interface = function() {
document.getElementById('top-box').innerHTML = '<h1 id="sentence" class="main-sentence"></h1>';
boxGame = document.getElementById('box-game');
sentence = document.getElementById('sentence');
answerBox = document.getElementById('answer-box');
if (this.mode == '1') {
answerBox.innerHTML =
'<h2 class="option-title">Selecciona la palabra correcta</h2>' +
'<div class="col-1-2" id="col-left">' +
' <button id="op1"></button>' +
'</div>' +
'<div class="col-1-2" id="col-right">' +
' <button id="op2"></button>' +
'</div>';
var op1 = document.getElementById('op1');
var op2 = document.getElementById('op2');
op1.addEventListener('click', function() {
game.checkAnswer(this.innerHTML);
});
op2.addEventListener('click', function() {
game.checkAnswer(this.innerHTML);
});
}
else if (this.mode == '2') {
answerBox.innerHTML =
'<h2 class="option-title">Escribe la letra que falta</h2>' +
'<input type="text" id="answer">';
var answerInput = document.getElementById('answer');
answerInput.addEventListener('input', function() {
game.checkAnswer(this.value);
this.value = '';
});
}
this.start();
}
this.showError = function() {
var topBox = document.getElementById('top-box');
var answerBox = document.getElementById('answer-box');
topBox.innerHTML =
'<h1>¡Has fallado...!</h1>'+
'<a href="#" id="restart">Vuelve a intentarlo»</a>';
document.getElementById('restart').addEventListener('click', this.interface.bind(this), false);
if (this.mode == '1') {
answerBox.innerHTML =
'<h2 class="error-title">Aprende la diferencia</h2>' +
'<div class="col-1-2" id="col-left">' +
'<p class="definition-word">' + this.currentWord['op1'] + '</p>' +
'<p class="definition">' + this.currentWord['op1_concept'] + '</p>' +
'</div>' +
'<div class="col-1-2" id="col-right">' +
'<p class="definition-word">' + this.currentWord['op2'] + '</p>' +
'<p class="definition">' + this.currentWord['op2_concept'] + '</p>' +
'</div>';
}
else if (this.mode == '2') {
answerBox.innerHTML =
'<h2 class="error-title">Aprende la regla:</h2>' +
'<p class="rule">' + this.currentWord['concept'] + '</p>';
}
}
this.setBar = function() {
var bar = document.getElementById('point-bar');
bar.innerHTML = '';
for (var i = this.point_count; i > 0; i--) {
bar.innerHTML += '<span class="star"></span>';
}
}
var self = this;
this.checkAnswer = function(answer) {
if (answer.toLowerCase() == this.answer.toLowerCase()) {
this.error_count = 0;
this.point_count += 1;
// Siguiente pregunta
$('#walking-character').sprite({
fps: 3,
no_of_frames: 3,
play_frames: 3
});
if (this.point_count < this.win_level) {
this.setBar();
this.start();
}
// Fin de nivel
else {
// var approvedLevels = JSON.parse(localStorage['level']);
// approvedLevels[parseInt(this.level) - 1] = true;
// localStorage['level'] = JSON.stringify(approvedLevels);
// dictstore.save();
// Fin de juego
if (count(this.data_level) >= 12) {
document.getElementById('history-end').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
document.getElementById('end-next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('history-end').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
$('#land').spStop(true);
});
}
else {
var topBox = document.getElementById('top-box');
var answerBox = document.getElementById('answer-box');
topBox.innerHTML =
'<h1>¡Felicidades, has completado este mundo!</h1>';
answerBox.innerHTML =
'<p><strong>Has ganado una medalla</strong></p>' +
'<p><span class="medal"></span></p>' +
'<p><button id="next">Continuar</button></p>';
document.getElementById('next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
$('#land').spStop(true);
});
}
}
}
else {
this.error_count += 1;
if (this.point_count > 0) {
this.point_count = this.point_count - 1;
this.setBar();
}
if (this.error_count >= 5) {
this.error_count = 0;
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
$('#land').spStop(true);
}
else {
this.showError();
}
}
}
}
require(['domReady!'], function (doc) {
activity.setup();
game = new Game();
document.getElementById('boy').addEventListener('click', function() {
document.getElementById('character').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
document.getElementById('history-gender').innerHTML =
"Lalo debe encontrar a su hermana y tienes la misión de ayudarle.";
document.getElementById('end-gender').innerHTML = "Lola";
document.getElementById('world-character').className = 'boy-world';
game.character = 1;
});
document.getElementById('girl').addEventListener('click', function() {
document.getElementById('character').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
document.getElementById('history-gender').innerHTML =
"Lola debe encontrar a su hermano y tienes la misión de ayudarle.";
document.getElementById('end-gender').innerHTML = "Lalo";
document.getElementById('world-character').className = 'girl-world';
game.character = 2;
});
document.getElementById('history-next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
});
document.getElementById('1').addEventListener('click', function() {
game.init('1', '2');
});
document.getElementById('2').addEventListener('click', function() {
game.init('2', '2');
});
document.getElementById('3').addEventListener('click', function() {
game.init('3', '2');
});
document.getElementById('4').addEventListener('click', function() {
game.init('4', '2');
});
document.getElementById('5').addEventListener('click', function() {
game.init('5', '2');
});
document.getElementById('6').addEventListener('click', function() {
game.init('6', '2');
});
document.getElementById('7').addEventListener('click', function() {
game.init('7', '2');
});
document.getElementById('8').addEventListener('click', function() {
game.init('8', '2');
});
document.getElementById('9').addEventListener('click', function() {
game.init('9', '1');
});
document.getElementById('10').addEventListener('click', function() {
game.init('10', '1');
});
document.getElementById('11').addEventListener('click', function() {
game.init('11', '1');
});
document.getElementById('12').addEventListener('click', function() {
game.init('12', '1');
});
});
});
| js/activity.js | define(function (require) {
var jquery = require("jquery");
var activity = require("sugar-web/activity/activity");
var palette = require("sugar-web/graphics/palette");
var icon = require("sugar-web/graphics/icon");
var dictstore = require("sugar-web/dictstore")
var l10n = require("webL10n");
var spritely = require("spritely");
var words = null;
function count(array) {
var counter = 0;
for (var i = 0; i < array.length; i++) {
if (array[i]) {
counter++;
}
}
return counter;
}
function getWords(level) {
if (words == null) {
words = require("words");
}
return words[level][Math.floor(Math.random() * (words[level].length))];
}
function Game() {
this.level = null;
this.mode = null;
this.currentWord = [];
this.answer = '';
this.boxGame = null;
this.sentence = null;
this.answerBox = null;
this.error_count = 0;
this.point_count = 0;
this.win_level = 0;
this.character = 0;
this.data_level = Array(12);
function onStoreReady() {
if (localStorage['level']) {
this.data_level = JSON.parse(localStorage['level']);
console.log(this.data_level);
for (var i = 1; i <= this.data_level.length; i++) {
if (this.data_level[i - 1]) {
document.getElementById(String(i)).className = 'world world-'+ i +' done';
}
}
}
}
dictstore.init(onStoreReady);
this.init = function(level, mode) {
this.level = level;
this.mode = mode;
this.point_count = 0;
if (this.mode == '1') {
this.win_level = 70;
}
else if (this.mode == '2') {
this.win_level = 40;
}
document.getElementById('point-bar').innerHTML = '';
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
/*
I didn't expect to use JQuery at the beginning, but it's required
by the animation library.
I hope you love spaguetti code.
*/
$('#land').css('background', 'url(../images/land-' + level + '.png) left top repeat-x');
$('#land').pan({fps: 30, speed: 0.7, dir: 'left'});
$('#land').spStart();
console.log('Iniciar animacion');
if (this.character == 1) {
document.getElementById('walking-character').className = 'boy-' + level;
}
else {
document.getElementById('walking-character').className = 'girl-' + level;
}
this.interface();
}
this.start = function() {
this.currentWord = getWords(this.level);
this.answer = this.currentWord['answer'];
sentence.innerHTML = this.currentWord['sentence'];
if (sentence.className == 'main-sentence') {
sentence.className = '';
}
if (this.mode == '1') {
document.getElementById('op1').innerHTML = this.currentWord['op1'];
document.getElementById('op2').innerHTML = this.currentWord['op2'];
}
}
this.interface = function() {
document.getElementById('top-box').innerHTML = '<h1 id="sentence" class="main-sentence"></h1>';
boxGame = document.getElementById('box-game');
sentence = document.getElementById('sentence');
answerBox = document.getElementById('answer-box');
if (this.mode == '1') {
answerBox.innerHTML =
'<h2 class="option-title">Selecciona la palabra correcta</h2>' +
'<div class="col-1-2" id="col-left">' +
' <button id="op1"></button>' +
'</div>' +
'<div class="col-1-2" id="col-right">' +
' <button id="op2"></button>' +
'</div>';
var op1 = document.getElementById('op1');
var op2 = document.getElementById('op2');
op1.addEventListener('click', function() {
game.checkAnswer(this.innerHTML);
});
op2.addEventListener('click', function() {
game.checkAnswer(this.innerHTML);
});
}
else if (this.mode == '2') {
answerBox.innerHTML =
'<h2 class="option-title">Escribe la letra que falta</h2>' +
'<input type="text" id="answer">';
var answerInput = document.getElementById('answer');
answerInput.addEventListener('input', function() {
game.checkAnswer(this.value);
this.value = '';
});
}
this.start();
}
this.showError = function() {
var topBox = document.getElementById('top-box');
var answerBox = document.getElementById('answer-box');
topBox.innerHTML =
'<h1>¡Has fallado...!</h1>'+
'<a href="#" id="restart">Vuelve a intentarlo»</a>';
document.getElementById('restart').addEventListener('click', this.interface.bind(this), false);
if (this.mode == '1') {
answerBox.innerHTML =
'<h2 class="error-title">Aprende la diferencia</h2>' +
'<div class="col-1-2" id="col-left">' +
'<p class="definition-word">' + this.currentWord['op1'] + '</p>' +
'<p class="definition">' + this.currentWord['op1_concept'] + '</p>' +
'</div>' +
'<div class="col-1-2" id="col-right">' +
'<p class="definition-word">' + this.currentWord['op2'] + '</p>' +
'<p class="definition">' + this.currentWord['op2_concept'] + '</p>' +
'</div>';
}
else if (this.mode == '2') {
answerBox.innerHTML =
'<h2 class="error-title">Aprende la regla:</h2>' +
'<p class="rule">' + this.currentWord['concept'] + '</p>';
}
}
this.setBar = function() {
var bar = document.getElementById('point-bar');
bar.innerHTML = '';
for (var i = this.point_count; i > 0; i--) {
bar.innerHTML += '<span class="star"></span>';
}
}
var self = this;
this.checkAnswer = function(answer) {
if (answer.toLowerCase() == this.answer.toLowerCase()) {
this.error_count = 0;
this.point_count += 1;
// Siguiente pregunta
$('#walking-character').sprite({
fps: 3,
no_of_frames: 3,
play_frames: 3
});
if (this.point_count < this.win_level) {
this.setBar();
this.start();
}
// Fin de nivel
else {
var approvedLevels = JSON.parse(localStorage['level']);
approvedLevels[parseInt(this.level) - 1] = true;
localStorage['level'] = JSON.stringify(approvedLevels);
dictstore.save();
// Fin de juego
if (count(this.data_level) >= 12) {
document.getElementById('history-end').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
document.getElementById('end-next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('history-end').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
$('#land').spStop(true);
});
}
else {
var topBox = document.getElementById('top-box');
var answerBox = document.getElementById('answer-box');
topBox.innerHTML =
'<h1>¡Felicidades, has completado este mundo!</h1>';
answerBox.innerHTML =
'<p><strong>Has ganado una medalla</strong></p>' +
'<p><span class="medal"></span></p>' +
'<p><button id="next">Continuar</button></p>';
document.getElementById('next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
$('#land').spStop(true);
});
}
}
}
else {
this.error_count += 1;
if (this.point_count > 0) {
this.point_count = this.point_count - 1;
this.setBar();
}
if (this.error_count >= 5) {
this.error_count = 0;
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('land').classList.toggle('hidden');
document.getElementById('box-game').classList.toggle('hidden');
document.getElementById('point-bar').classList.toggle('hidden');
document.getElementById('walking-character').className = 'hidden';
$('#land').spStop(true);
}
else {
this.showError();
}
}
}
}
require(['domReady!'], function (doc) {
activity.setup();
game = new Game();
document.getElementById('boy').addEventListener('click', function() {
document.getElementById('character').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
document.getElementById('history-gender').innerHTML =
"Lalo debe encontrar a su hermana y tienes la misión de ayudarle.";
document.getElementById('end-gender').innerHTML = "Lola";
document.getElementById('world-character').className = 'boy-world';
game.character = 1;
});
document.getElementById('girl').addEventListener('click', function() {
document.getElementById('character').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
document.getElementById('history-gender').innerHTML =
"Lola debe encontrar a su hermano y tienes la misión de ayudarle.";
document.getElementById('end-gender').innerHTML = "Lalo";
document.getElementById('world-character').className = 'girl-world';
game.character = 2;
});
document.getElementById('history-next').addEventListener('click', function() {
document.getElementById('world-menu').classList.toggle('hidden');
document.getElementById('history').classList.toggle('hidden');
});
document.getElementById('1').addEventListener('click', function() {
game.init('1', '2');
});
document.getElementById('2').addEventListener('click', function() {
game.init('2', '2');
});
document.getElementById('3').addEventListener('click', function() {
game.init('3', '2');
});
document.getElementById('4').addEventListener('click', function() {
game.init('4', '2');
});
document.getElementById('5').addEventListener('click', function() {
game.init('5', '2');
});
document.getElementById('6').addEventListener('click', function() {
game.init('6', '2');
});
document.getElementById('7').addEventListener('click', function() {
game.init('7', '2');
});
document.getElementById('8').addEventListener('click', function() {
game.init('8', '2');
});
document.getElementById('9').addEventListener('click', function() {
game.init('9', '1');
});
document.getElementById('10').addEventListener('click', function() {
game.init('10', '1');
});
document.getElementById('11').addEventListener('click', function() {
game.init('11', '1');
});
document.getElementById('12').addEventListener('click', function() {
game.init('12', '1');
});
});
});
| Quitar temporalmente almacenamiento local
| js/activity.js | Quitar temporalmente almacenamiento local | <ide><path>s/activity.js
<ide>
<ide> // Fin de nivel
<ide> else {
<del> var approvedLevels = JSON.parse(localStorage['level']);
<del> approvedLevels[parseInt(this.level) - 1] = true;
<del> localStorage['level'] = JSON.stringify(approvedLevels);
<del> dictstore.save();
<add> // var approvedLevels = JSON.parse(localStorage['level']);
<add> // approvedLevels[parseInt(this.level) - 1] = true;
<add> // localStorage['level'] = JSON.stringify(approvedLevels);
<add> // dictstore.save();
<ide>
<ide> // Fin de juego
<ide> if (count(this.data_level) >= 12) { |
|
Java | epl-1.0 | 30bcb8fced08dc0acfc2bf82b2ace5d9174eea5e | 0 | JanMosigItemis/codingdojoleipzig | package de.itemis.mosig.racecar.tirepressure;
public class Alarm
{
private final double LowPressureThreshold = 17;
private final double HighPressureThreshold = 21;
private final Sensor sensor;
private boolean alarmOn = false;
public Alarm(Sensor sensor) {
this.sensor = sensor;
}
public void check() {
double psiPressureValue = sensor.popNextPressurePsiValue();
alarmOn = psiPressureValue < LowPressureThreshold || HighPressureThreshold < psiPressureValue;
}
public boolean isAlarmOn() {
return alarmOn;
}
}
| racecar/TirePressureMonitoringSystem/pattern_solution/src/main/java/de/itemis/mosig/racecar/tirepressure/Alarm.java | package de.itemis.mosig.racecar.tirepressure;
public class Alarm
{
private final double LowPressureThreshold = 17;
private final double HighPressureThreshold = 21;
private final Sensor sensor;
private boolean alarmOn = false;
public Alarm(Sensor sensor) {
this.sensor = sensor;
}
public void check()
{
double psiPressureValue = sensor.popNextPressurePsiValue();
if (psiPressureValue < LowPressureThreshold || HighPressureThreshold < psiPressureValue)
{
alarmOn = true;
}
}
public boolean isAlarmOn()
{
return alarmOn;
}
}
| GREEN: Alarm can now be turned off.
| racecar/TirePressureMonitoringSystem/pattern_solution/src/main/java/de/itemis/mosig/racecar/tirepressure/Alarm.java | GREEN: Alarm can now be turned off. | <ide><path>acecar/TirePressureMonitoringSystem/pattern_solution/src/main/java/de/itemis/mosig/racecar/tirepressure/Alarm.java
<ide> this.sensor = sensor;
<ide> }
<ide>
<del> public void check()
<del> {
<add> public void check() {
<ide> double psiPressureValue = sensor.popNextPressurePsiValue();
<ide>
<del> if (psiPressureValue < LowPressureThreshold || HighPressureThreshold < psiPressureValue)
<del> {
<del> alarmOn = true;
<del> }
<add> alarmOn = psiPressureValue < LowPressureThreshold || HighPressureThreshold < psiPressureValue;
<ide> }
<ide>
<del> public boolean isAlarmOn()
<del> {
<add> public boolean isAlarmOn() {
<ide> return alarmOn;
<ide> }
<ide> } |
|
JavaScript | mit | c1f37e767ff03adfccd447d31c5f2f097a3b4eee | 0 | angelozerr/tern-jasmine,angelozerr/tern-jasmine | (function(mod) {
if (typeof exports == "object" && typeof module == "object") { // CommonJS
return mod(require.main.require("../lib/infer"), require.main.require("../lib/tern"));
}
if (typeof define == "function" && define.amd) // AMD
return define([ "tern/lib/infer", "tern/lib/tern" ], mod);
mod(tern, tern);
})(function(infer, tern) {
"use strict";
tern.registerPlugin("jasmine", function(server, options) {
return {
defs : defs
};
});
var defs = {
"!name": "jasmine",
"describe": {
"!type": "fn(description: string, specDefinitions: fn())",
"!doc": "A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite."
},
"it": {
"!type": "fn(description: string, specDefinitions: fn())",
"!doc": "Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec."
}
}
}); | jasmine.js | (function(mod) {
if (typeof exports == "object" && typeof module == "object") { // CommonJS
return mod(require.main.require("../lib/infer"), require.main.require("../lib/tern"));
}
if (typeof define == "function" && define.amd) // AMD
return define([ "tern/lib/infer", "tern/lib/tern" ], mod);
mod(tern, tern);
})(function(infer, tern) {
"use strict";
tern.registerPlugin("jasmine", function(server, options) {
return {
defs : defs
};
});
var defs = {
"!name": "jasmine",
"describe": {
"!type": "fn(description: string, specDefinitions: fn())",
"!doc": "A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite."
},
"it": {
"!type": "fn(description: string, specDefinitions: fn())",
"!doc": "Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec."
}
}
}); | Remove tab | jasmine.js | Remove tab | <ide><path>asmine.js
<ide> });
<ide>
<ide> var defs = {
<del> "!name": "jasmine",
<del> "describe": {
<del> "!type": "fn(description: string, specDefinitions: fn())",
<del> "!doc": "A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite."
<del> },
<del> "it": {
<add> "!name": "jasmine",
<add> "describe": {
<add> "!type": "fn(description: string, specDefinitions: fn())",
<add> "!doc": "A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite."
<add> },
<add> "it": {
<ide> "!type": "fn(description: string, specDefinitions: fn())",
<ide> "!doc": "Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec."
<ide> } |
|
Java | apache-2.0 | 05ab71038e7f180fdebcabad7e79190e276618e9 | 0 | anton-antonenko/jagger,amikryukov/newJagger,vladimir-bukhtoyarov/jagger,SokolAndrey/jagger,anton-antonenko/jagger,amikryukov/jagger,vladimir-bukhtoyarov/jagger,vladimir-bukhtoyarov/jagger8,dlatnikov/jagger,Nmishin/jagger,Nmishin/jagger,vladimir-bukhtoyarov/jagger8,anton-antonenko/jagger,dlatnikov/jagger,vladimir-bukhtoyarov/jagger8,SokolAndrey/jagger,griddynamics/jagger,griddynamics/jagger,Nmishin/jagger,vladimir-bukhtoyarov/jagger,amikryukov/newJagger,SokolAndrey/jagger,griddynamics/jagger,amikryukov/jagger | package com.griddynamics.jagger.xml.beanParsers.report;
import com.griddynamics.jagger.engine.e1.reporting.OverallSessionComparisonReporter;
import com.griddynamics.jagger.engine.e1.sessioncomparation.BaselineSessionProvider;
import com.griddynamics.jagger.extension.ExtensionRegistry;
import com.griddynamics.jagger.reporting.ReportingContext;
import com.griddynamics.jagger.reporting.ReportingService;
import com.griddynamics.jagger.xml.beanParsers.CustomBeanDefinitionParser;
import com.griddynamics.jagger.xml.beanParsers.XMLConstants;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Created by IntelliJ IDEA.
* User: nmusienko
* Date: 03.12.12
* Time: 19:26
* To change this template use File | Settings | File Templates.
*/
public class ReportDefinitionParser extends AbstractSimpleBeanDefinitionParser {
@Override
protected Class getBeanClass(Element element) {
return ReportingService.class;
}
@Override
public void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
super.doParse(element,parserContext,builder);
builder.setParentName(XMLConstants.DEFAULT_REPORTING_SERVICE);
//parse extensions
Element extensionsElement = DomUtils.getChildElementByTagName(element, XMLConstants.EXTENSIONS);
if (extensionsElement != null)
parserContext.getDelegate().parseCustomElement(extensionsElement);
Element sessionComparatorsElement = DomUtils.getChildElementByTagName(element, XMLConstants.SESSION_COMPARATORS_ELEMENT);
if (sessionComparatorsElement != null){
//context
BeanDefinitionBuilder reportContext = BeanDefinitionBuilder.genericBeanDefinition(ReportingContext.class);
reportContext.setParentName(XMLConstants.REPORTING_CONTEXT);
String reportContextName = parserContext.getReaderContext().generateBeanName(reportContext.getBeanDefinition());
parserContext.getRegistry().registerBeanDefinition(reportContextName, reportContext.getBeanDefinition());
//parse comparators
BeanDefinitionBuilder registry = BeanDefinitionBuilder.genericBeanDefinition(ExtensionRegistry.class);
registry.setParentName(XMLConstants.REPORTER_REGISTRY);
BeanDefinitionBuilder comparisonReporter = BeanDefinitionBuilder.genericBeanDefinition(OverallSessionComparisonReporter.class);
comparisonReporter.setParentName(XMLConstants.REPORTER_COMPARISON);
//parse baselineProvider
BeanDefinitionBuilder baseLineSessionProvider = BeanDefinitionBuilder.genericBeanDefinition(BaselineSessionProvider.class);
baseLineSessionProvider.setParentName(XMLConstants.REPORTER_BASELINE_PROVIDER);
String baseLineId = sessionComparatorsElement.getAttribute(XMLConstants.BASELINE_ID);
if (!baseLineId.isEmpty()){
baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, baseLineId);
}else{
baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, BaselineSessionProvider.IDENTITY_SESSION);
}
comparisonReporter.addPropertyValue(XMLConstants.BASELINE_SESSION_PROVIDER, baseLineSessionProvider.getBeanDefinition());
//parse comparators chain
CustomBeanDefinitionParser.setBeanProperty(XMLConstants.SESSION_COMPARATOR, sessionComparatorsElement, parserContext, comparisonReporter.getBeanDefinition());
//set all parameters
ManagedMap registryMap = new ManagedMap();
registryMap.setMergeEnabled(true);
registryMap.put(XMLConstants.SESSION_COMPARISON, comparisonReporter.getBeanDefinition());
registry.addPropertyValue(XMLConstants.EXTENSIONS, registryMap);
reportContext.addPropertyValue(XMLConstants.PROVIDER_REGISTRY, registry.getBeanDefinition());
//set context
comparisonReporter.addPropertyReference(XMLConstants.CONTEXT, reportContextName);
builder.addPropertyReference(XMLConstants.CONTEXT, reportContextName);
}
}
}
| chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/report/ReportDefinitionParser.java | package com.griddynamics.jagger.xml.beanParsers.report;
import com.griddynamics.jagger.engine.e1.reporting.OverallSessionComparisonReporter;
import com.griddynamics.jagger.engine.e1.sessioncomparation.BaselineSessionProvider;
import com.griddynamics.jagger.extension.ExtensionRegistry;
import com.griddynamics.jagger.reporting.ReportingContext;
import com.griddynamics.jagger.reporting.ReportingService;
import com.griddynamics.jagger.xml.beanParsers.XMLConstants;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Created by IntelliJ IDEA.
* User: nmusienko
* Date: 03.12.12
* Time: 19:26
* To change this template use File | Settings | File Templates.
*/
public class ReportDefinitionParser extends AbstractSimpleBeanDefinitionParser {
@Override
protected Class getBeanClass(Element element) {
return ReportingService.class;
}
@Override
public void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
super.doParse(element,parserContext,builder);
builder.setParentName(XMLConstants.DEFAULT_REPORTING_SERVICE);
//TODO
Element extensionsElement = DomUtils.getChildElementByTagName(element, XMLConstants.EXTENSIONS);
if (extensionsElement != null)
parserContext.getDelegate().parseCustomElement(extensionsElement);
//parse comparators
BeanDefinitionBuilder registry = BeanDefinitionBuilder.genericBeanDefinition(ExtensionRegistry.class);
registry.setParentName(XMLConstants.REPORTER_REGISTRY);
BeanDefinitionBuilder comparisonReporter = BeanDefinitionBuilder.genericBeanDefinition(OverallSessionComparisonReporter.class);
comparisonReporter.setParentName(XMLConstants.REPORTER_COMPARISON);
//parse baselineProvider
BeanDefinitionBuilder baseLineSessionProvider = BeanDefinitionBuilder.genericBeanDefinition(BaselineSessionProvider.class);
baseLineSessionProvider.setParentName(XMLConstants.REPORTER_BASELINE_PROVIDER);
Element sessionComparatorsElement = DomUtils.getChildElementByTagName(element, XMLConstants.SESSION_COMPARATORS_ELEMENT);
if (sessionComparatorsElement != null){
String baseLineId = sessionComparatorsElement.getAttribute(XMLConstants.BASELINE_ID);
if (!baseLineId.isEmpty()){
baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, baseLineId);
}else{
baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, BaselineSessionProvider.IDENTITY_SESSION);
}
BeanDefinition comparators = parserContext.getDelegate().parseCustomElement(sessionComparatorsElement, builder.getBeanDefinition());
comparisonReporter.addPropertyValue(XMLConstants.SESSION_COMPARATOR, comparators);
}
comparisonReporter.addPropertyValue(XMLConstants.BASELINE_SESSION_PROVIDER, baseLineSessionProvider.getBeanDefinition());
ManagedMap registryMap = new ManagedMap();
registryMap.put(XMLConstants.SESSION_COMPARISON, comparisonReporter.getBeanDefinition());
registry.addPropertyValue(XMLConstants.EXTENSIONS, registryMap);
BeanDefinitionBuilder reportContext = BeanDefinitionBuilder.genericBeanDefinition(ReportingContext.class);
reportContext.setParentName(XMLConstants.REPORTING_CONTEXT);
reportContext.addPropertyValue(XMLConstants.PROVIDER_REGISTRY, registry.getBeanDefinition());
builder.addPropertyValue(XMLConstants.CONTEXT, reportContext.getBeanDefinition());
}
}
| Fix report parsing
| chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/report/ReportDefinitionParser.java | Fix report parsing | <ide><path>hassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/report/ReportDefinitionParser.java
<ide> import com.griddynamics.jagger.extension.ExtensionRegistry;
<ide> import com.griddynamics.jagger.reporting.ReportingContext;
<ide> import com.griddynamics.jagger.reporting.ReportingService;
<add>import com.griddynamics.jagger.xml.beanParsers.CustomBeanDefinitionParser;
<ide> import com.griddynamics.jagger.xml.beanParsers.XMLConstants;
<del>import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide> import org.springframework.beans.factory.support.ManagedMap;
<ide> import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
<ide>
<ide> builder.setParentName(XMLConstants.DEFAULT_REPORTING_SERVICE);
<ide>
<del> //TODO
<add> //parse extensions
<ide> Element extensionsElement = DomUtils.getChildElementByTagName(element, XMLConstants.EXTENSIONS);
<ide> if (extensionsElement != null)
<ide> parserContext.getDelegate().parseCustomElement(extensionsElement);
<ide>
<del> //parse comparators
<del> BeanDefinitionBuilder registry = BeanDefinitionBuilder.genericBeanDefinition(ExtensionRegistry.class);
<del> registry.setParentName(XMLConstants.REPORTER_REGISTRY);
<del>
<del> BeanDefinitionBuilder comparisonReporter = BeanDefinitionBuilder.genericBeanDefinition(OverallSessionComparisonReporter.class);
<del> comparisonReporter.setParentName(XMLConstants.REPORTER_COMPARISON);
<del>
<del> //parse baselineProvider
<del> BeanDefinitionBuilder baseLineSessionProvider = BeanDefinitionBuilder.genericBeanDefinition(BaselineSessionProvider.class);
<del> baseLineSessionProvider.setParentName(XMLConstants.REPORTER_BASELINE_PROVIDER);
<del>
<ide> Element sessionComparatorsElement = DomUtils.getChildElementByTagName(element, XMLConstants.SESSION_COMPARATORS_ELEMENT);
<ide>
<ide> if (sessionComparatorsElement != null){
<add>
<add> //context
<add> BeanDefinitionBuilder reportContext = BeanDefinitionBuilder.genericBeanDefinition(ReportingContext.class);
<add> reportContext.setParentName(XMLConstants.REPORTING_CONTEXT);
<add> String reportContextName = parserContext.getReaderContext().generateBeanName(reportContext.getBeanDefinition());
<add> parserContext.getRegistry().registerBeanDefinition(reportContextName, reportContext.getBeanDefinition());
<add>
<add> //parse comparators
<add> BeanDefinitionBuilder registry = BeanDefinitionBuilder.genericBeanDefinition(ExtensionRegistry.class);
<add> registry.setParentName(XMLConstants.REPORTER_REGISTRY);
<add>
<add> BeanDefinitionBuilder comparisonReporter = BeanDefinitionBuilder.genericBeanDefinition(OverallSessionComparisonReporter.class);
<add> comparisonReporter.setParentName(XMLConstants.REPORTER_COMPARISON);
<add>
<add> //parse baselineProvider
<add> BeanDefinitionBuilder baseLineSessionProvider = BeanDefinitionBuilder.genericBeanDefinition(BaselineSessionProvider.class);
<add> baseLineSessionProvider.setParentName(XMLConstants.REPORTER_BASELINE_PROVIDER);
<add>
<ide> String baseLineId = sessionComparatorsElement.getAttribute(XMLConstants.BASELINE_ID);
<ide> if (!baseLineId.isEmpty()){
<ide> baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, baseLineId);
<ide> }else{
<ide> baseLineSessionProvider.addPropertyValue(XMLConstants.SESSION_ID, BaselineSessionProvider.IDENTITY_SESSION);
<ide> }
<add> comparisonReporter.addPropertyValue(XMLConstants.BASELINE_SESSION_PROVIDER, baseLineSessionProvider.getBeanDefinition());
<ide>
<del> BeanDefinition comparators = parserContext.getDelegate().parseCustomElement(sessionComparatorsElement, builder.getBeanDefinition());
<del> comparisonReporter.addPropertyValue(XMLConstants.SESSION_COMPARATOR, comparators);
<add> //parse comparators chain
<add> CustomBeanDefinitionParser.setBeanProperty(XMLConstants.SESSION_COMPARATOR, sessionComparatorsElement, parserContext, comparisonReporter.getBeanDefinition());
<add>
<add> //set all parameters
<add> ManagedMap registryMap = new ManagedMap();
<add> registryMap.setMergeEnabled(true);
<add> registryMap.put(XMLConstants.SESSION_COMPARISON, comparisonReporter.getBeanDefinition());
<add>
<add> registry.addPropertyValue(XMLConstants.EXTENSIONS, registryMap);
<add>
<add> reportContext.addPropertyValue(XMLConstants.PROVIDER_REGISTRY, registry.getBeanDefinition());
<add>
<add> //set context
<add> comparisonReporter.addPropertyReference(XMLConstants.CONTEXT, reportContextName);
<add>
<add> builder.addPropertyReference(XMLConstants.CONTEXT, reportContextName);
<ide> }
<del>
<del> comparisonReporter.addPropertyValue(XMLConstants.BASELINE_SESSION_PROVIDER, baseLineSessionProvider.getBeanDefinition());
<del>
<del> ManagedMap registryMap = new ManagedMap();
<del> registryMap.put(XMLConstants.SESSION_COMPARISON, comparisonReporter.getBeanDefinition());
<del>
<del> registry.addPropertyValue(XMLConstants.EXTENSIONS, registryMap);
<del>
<del> BeanDefinitionBuilder reportContext = BeanDefinitionBuilder.genericBeanDefinition(ReportingContext.class);
<del> reportContext.setParentName(XMLConstants.REPORTING_CONTEXT);
<del> reportContext.addPropertyValue(XMLConstants.PROVIDER_REGISTRY, registry.getBeanDefinition());
<del>
<del> builder.addPropertyValue(XMLConstants.CONTEXT, reportContext.getBeanDefinition());
<ide> }
<ide> } |
|
Java | apache-2.0 | b0664f12250a2bc2de80eb9ab5155fda390fc1e7 | 0 | klu2/structurizr-java,structurizr/java | package com.structurizr.api;
import com.structurizr.Workspace;
import com.structurizr.encryption.*;
import com.structurizr.io.json.JsonReader;
import com.structurizr.io.json.JsonWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Properties;
public class StructurizrClient {
private static final Log log = LogFactory.getLog(StructurizrClient.class);
public static final String STRUCTURIZR_API_URL = "structurizr.api.url";
public static final String STRUCTURIZR_API_KEY = "structurizr.api.key";
public static final String STRUCTURIZR_API_SECRET = "structurizr.api.secret";
private static final String WORKSPACE_PATH = "/workspace/";
private String url;
private String apiKey;
private String apiSecret;
private EncryptionStrategy encryptionStrategy;
/** the location where a copy of the workspace will be archived when it is retrieved from the server */
private File workspaceArchiveLocation = new File(".");
/**
* Creates a new Structurizr client based upon configuration in a structurizr.properties file
* on the classpath with the following name-value pairs:
* - structurizr.api.url
* - structurizr.api.key
* - structurizr.api.secret
*/
public StructurizrClient() {
try {
Properties properties = new Properties();
InputStream in = StructurizrClient.class.getClassLoader().getResourceAsStream("structurizr.properties");
if (in != null) {
properties.load(in);
setUrl(properties.getProperty(STRUCTURIZR_API_URL));
this.apiKey = properties.getProperty(STRUCTURIZR_API_KEY);
this.apiSecret = properties.getProperty(STRUCTURIZR_API_SECRET);
in.close();
}
} catch (Exception e) {
log.error(e);
}
}
/**
* Creates a new Structurizr client with the specified API key and secret.
*/
public StructurizrClient(String apiKey, String apiSecret) {
setUrl("https://api.structurizr.com");
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}
/**
* Creates a new Structurizr client with the specified API URL, key and secret.
*/
public StructurizrClient(String url, String apiKey, String apiSecret) {
setUrl(url);
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
if (url != null) {
if (url.endsWith("/")) {
this.url = url.substring(0, url.length() - 1);
} else {
this.url = url;
}
}
}
/**
* Gets the location where a copy of the workspace is archived when it is retrieved from the server.
*
* @return a File instance representing a directory, or null if this client instance is not archiving
*/
public File getWorkspaceArchiveLocation() {
return this.workspaceArchiveLocation;
}
/**
* Sets the location where a copy of the workspace will be archived whenever it is retrieved from
* the server. Set this to null if you don't want archiving.
*
* @param workspaceArchiveLocation a File instance representing a directory, or null if
* you don't want archiving
*/
public void setWorkspaceArchiveLocation(File workspaceArchiveLocation) {
this.workspaceArchiveLocation = workspaceArchiveLocation;
}
/**
* Sets the encryption strategy for use when getting or putting workspaces.
*
* @param encryptionStrategy an EncryptionStrategy implementation
*/
public void setEncryptionStrategy(EncryptionStrategy encryptionStrategy) {
this.encryptionStrategy = encryptionStrategy;
}
/**
* Gets the workspace with the given ID.
*
* @param workspaceId the ID of your workspace
* @return a Workspace instance
* @throws Exception if there are problems related to the network, authorization, JSON deserialization, etc
*/
public Workspace getWorkspace(long workspaceId) throws Exception {
log.info("Getting workspace with ID " + workspaceId);
CloseableHttpClient httpClient = HttpClients.createSystem();
HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId);
addHeaders(httpGet, "", "");
debugRequest(httpGet, null);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
debugResponse(response);
String json = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
archiveWorkspace(workspaceId, json);
if (encryptionStrategy == null) {
return new JsonReader().read(new StringReader(json));
} else {
EncryptedWorkspace encryptedWorkspace = new EncryptedJsonReader().read(new StringReader(json));
encryptedWorkspace.getEncryptionStrategy().setPassphrase(encryptionStrategy.getPassphrase());
return encryptedWorkspace.getWorkspace();
}
} else {
ApiError apiError = ApiError.parse(json);
throw new StructurizrClientException(apiError.getMessage());
}
}
}
/**
* Updates the given workspace.
*
* @param workspaceId the ID of your workspace
* @param workspace the workspace instance to update
* @throws Exception if there are problems related to the network, authorization, JSON serialization, etc
*/
public void putWorkspace(long workspaceId, Workspace workspace) throws Exception {
log.info("Putting workspace with ID " + workspaceId);
if (workspace == null) {
throw new IllegalArgumentException("A workspace must be supplied");
} else if (workspaceId <= 0) {
throw new IllegalArgumentException("The workspace ID must be set");
}
workspace.setId(workspaceId);
CloseableHttpClient httpClient = HttpClients.createSystem();
HttpPut httpPut = new HttpPut(url + WORKSPACE_PATH + workspaceId);
StringWriter stringWriter = new StringWriter();
if (encryptionStrategy == null) {
JsonWriter jsonWriter = new JsonWriter(false);
jsonWriter.write(workspace, stringWriter);
} else {
EncryptedWorkspace encryptedWorkspace = new EncryptedWorkspace(workspace, encryptionStrategy);
encryptionStrategy.setLocation(EncryptionLocation.Client);
EncryptedJsonWriter jsonWriter = new EncryptedJsonWriter(false);
jsonWriter.write(encryptedWorkspace, stringWriter);
}
StringEntity stringEntity = new StringEntity(stringWriter.toString(), ContentType.APPLICATION_JSON);
httpPut.setEntity(stringEntity);
addHeaders(httpPut, EntityUtils.toString(stringEntity), ContentType.APPLICATION_JSON.toString());
debugRequest(httpPut, EntityUtils.toString(stringEntity));
try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
String json = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
debugResponse(response);
log.info(json);
} else {
ApiError apiError = ApiError.parse(json);
throw new StructurizrClientException(apiError.getMessage());
}
}
}
/**
* Fetches the workspace with the given workspaceId from the server and merges its layout information with
* the given workspace. All models from the the new workspace are taken, only the old layout information is preserved.
*
* @param workspaceId the ID of your workspace
* @param workspace the new workspace
* @throws Exception if you are not allowed to update the workspace with the given ID or there are any network troubles
*/
public void mergeWorkspace(long workspaceId, Workspace workspace) throws Exception {
log.info("Merging workspace with ID " + workspaceId);
Workspace currentWorkspace = getWorkspace(workspaceId);
if (currentWorkspace != null) {
workspace.getViews().copyLayoutInformationFrom(currentWorkspace.getViews());
}
putWorkspace(workspaceId, workspace);
}
private void debugRequest(HttpRequestBase httpRequest, String content) {
log.debug(httpRequest.getMethod() + " " + httpRequest.getURI().getPath());
Header[] headers = httpRequest.getAllHeaders();
for (Header header : headers) {
log.debug(header.getName() + ": " + header.getValue());
}
if (content != null) {
log.debug(content);
}
}
private void debugResponse(CloseableHttpResponse response) {
log.debug(response.getStatusLine());
}
private void addHeaders(HttpRequestBase httpRequest, String content, String contentType) throws Exception {
String httpMethod = httpRequest.getMethod();
String path = httpRequest.getURI().getPath();
String contentMd5 = new Md5Digest().generate(content);
String nonce = "" + System.currentTimeMillis();
HashBasedMessageAuthenticationCode hmac = new HashBasedMessageAuthenticationCode(apiSecret);
HmacContent hmacContent = new HmacContent(httpMethod, path, contentMd5, contentType, nonce);
httpRequest.addHeader(HttpHeaders.AUTHORIZATION, new HmacAuthorizationHeader(apiKey, hmac.generate(hmacContent.toString())).format());
httpRequest.addHeader(HttpHeaders.NONCE, nonce);
httpRequest.addHeader(HttpHeaders.CONTENT_MD5, Base64.getEncoder().encodeToString(contentMd5.getBytes("UTF-8")));
httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
private void archiveWorkspace(long workspaceId, String json) {
if (this.workspaceArchiveLocation == null) {
return;
}
File archiveFile = new File(workspaceArchiveLocation, createArchiveFileName(workspaceId));
try {
FileWriter fileWriter = new FileWriter(archiveFile);
fileWriter.write(json);
fileWriter.flush();
fileWriter.close();
try {
log.debug("Workspace from server archived to " + archiveFile.getCanonicalPath());
} catch (IOException ioe) {
log.debug("Workspace from server archived to " + archiveFile.getAbsolutePath());
}
} catch (Exception e) {
log.warn("Could not archive JSON to " + archiveFile.getAbsolutePath());
}
}
private String createArchiveFileName(long workspaceId) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return "structurizr-" + workspaceId + "-" + sdf.format(new Date()) + ".json";
}
} | structurizr-client/src/com/structurizr/api/StructurizrClient.java | package com.structurizr.api;
import com.structurizr.Workspace;
import com.structurizr.encryption.*;
import com.structurizr.io.json.JsonReader;
import com.structurizr.io.json.JsonWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Properties;
public class StructurizrClient {
private static final Log log = LogFactory.getLog(StructurizrClient.class);
public static final String STRUCTURIZR_API_URL = "structurizr.api.url";
public static final String STRUCTURIZR_API_KEY = "structurizr.api.key";
public static final String STRUCTURIZR_API_SECRET = "structurizr.api.secret";
private static final String WORKSPACE_PATH = "/workspace/";
private String url;
private String apiKey;
private String apiSecret;
private EncryptionStrategy encryptionStrategy;
/** the location where a copy of the workspace will be archived when it is retrieved from the server */
private File workspaceArchiveLocation = new File(".");
/**
* Creates a new Structurizr client based upon configuration in a structurizr.properties file
* on the classpath with the following name-value pairs:
* - structurizr.api.url
* - structurizr.api.key
* - structurizr.api.secret
*/
public StructurizrClient() {
try {
Properties properties = new Properties();
InputStream in = StructurizrClient.class.getClassLoader().getResourceAsStream("structurizr.properties");
if (in != null) {
properties.load(in);
setUrl(properties.getProperty(STRUCTURIZR_API_URL));
this.apiKey = properties.getProperty(STRUCTURIZR_API_KEY);
this.apiSecret = properties.getProperty(STRUCTURIZR_API_SECRET);
in.close();
}
} catch (Exception e) {
log.error(e);
}
}
/**
* Creates a new Structurizr client with the specified API URL, key and secret.
*/
public StructurizrClient(String url, String apiKey, String apiSecret) {
setUrl(url);
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
if (url != null) {
if (url.endsWith("/")) {
this.url = url.substring(0, url.length() - 1);
} else {
this.url = url;
}
}
}
/**
* Gets the location where a copy of the workspace is archived when it is retrieved from the server.
*
* @return a File instance representing a directory, or null if this client instance is not archiving
*/
public File getWorkspaceArchiveLocation() {
return this.workspaceArchiveLocation;
}
/**
* Sets the location where a copy of the workspace will be archived whenever it is retrieved from
* the server. Set this to null if you don't want archiving.
*
* @param workspaceArchiveLocation a File instance representing a directory, or null if
* you don't want archiving
*/
public void setWorkspaceArchiveLocation(File workspaceArchiveLocation) {
this.workspaceArchiveLocation = workspaceArchiveLocation;
}
/**
* Sets the encryption strategy for use when getting or putting workspaces.
*
* @param encryptionStrategy an EncryptionStrategy implementation
*/
public void setEncryptionStrategy(EncryptionStrategy encryptionStrategy) {
this.encryptionStrategy = encryptionStrategy;
}
/**
* Gets the workspace with the given ID.
*
* @param workspaceId the ID of your workspace
* @return a Workspace instance
* @throws Exception if there are problems related to the network, authorization, JSON deserialization, etc
*/
public Workspace getWorkspace(long workspaceId) throws Exception {
log.info("Getting workspace with ID " + workspaceId);
CloseableHttpClient httpClient = HttpClients.createSystem();
HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId);
addHeaders(httpGet, "", "");
debugRequest(httpGet, null);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
debugResponse(response);
String json = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
archiveWorkspace(workspaceId, json);
if (encryptionStrategy == null) {
return new JsonReader().read(new StringReader(json));
} else {
EncryptedWorkspace encryptedWorkspace = new EncryptedJsonReader().read(new StringReader(json));
encryptedWorkspace.getEncryptionStrategy().setPassphrase(encryptionStrategy.getPassphrase());
return encryptedWorkspace.getWorkspace();
}
} else {
ApiError apiError = ApiError.parse(json);
throw new StructurizrClientException(apiError.getMessage());
}
}
}
/**
* Updates the given workspace.
*
* @param workspaceId the ID of your workspace
* @param workspace the workspace instance to update
* @throws Exception if there are problems related to the network, authorization, JSON serialization, etc
*/
public void putWorkspace(long workspaceId, Workspace workspace) throws Exception {
log.info("Putting workspace with ID " + workspaceId);
if (workspace == null) {
throw new IllegalArgumentException("A workspace must be supplied");
} else if (workspaceId <= 0) {
throw new IllegalArgumentException("The workspace ID must be set");
}
workspace.setId(workspaceId);
CloseableHttpClient httpClient = HttpClients.createSystem();
HttpPut httpPut = new HttpPut(url + WORKSPACE_PATH + workspaceId);
StringWriter stringWriter = new StringWriter();
if (encryptionStrategy == null) {
JsonWriter jsonWriter = new JsonWriter(false);
jsonWriter.write(workspace, stringWriter);
} else {
EncryptedWorkspace encryptedWorkspace = new EncryptedWorkspace(workspace, encryptionStrategy);
encryptionStrategy.setLocation(EncryptionLocation.Client);
EncryptedJsonWriter jsonWriter = new EncryptedJsonWriter(false);
jsonWriter.write(encryptedWorkspace, stringWriter);
}
StringEntity stringEntity = new StringEntity(stringWriter.toString(), ContentType.APPLICATION_JSON);
httpPut.setEntity(stringEntity);
addHeaders(httpPut, EntityUtils.toString(stringEntity), ContentType.APPLICATION_JSON.toString());
debugRequest(httpPut, EntityUtils.toString(stringEntity));
try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
String json = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
debugResponse(response);
log.info(json);
} else {
ApiError apiError = ApiError.parse(json);
throw new StructurizrClientException(apiError.getMessage());
}
}
}
/**
* Fetches the workspace with the given workspaceId from the server and merges its layout information with
* the given workspace. All models from the the new workspace are taken, only the old layout information is preserved.
*
* @param workspaceId the ID of your workspace
* @param workspace the new workspace
* @throws Exception if you are not allowed to update the workspace with the given ID or there are any network troubles
*/
public void mergeWorkspace(long workspaceId, Workspace workspace) throws Exception {
log.info("Merging workspace with ID " + workspaceId);
Workspace currentWorkspace = getWorkspace(workspaceId);
if (currentWorkspace != null) {
workspace.getViews().copyLayoutInformationFrom(currentWorkspace.getViews());
}
putWorkspace(workspaceId, workspace);
}
private void debugRequest(HttpRequestBase httpRequest, String content) {
log.debug(httpRequest.getMethod() + " " + httpRequest.getURI().getPath());
Header[] headers = httpRequest.getAllHeaders();
for (Header header : headers) {
log.debug(header.getName() + ": " + header.getValue());
}
if (content != null) {
log.debug(content);
}
}
private void debugResponse(CloseableHttpResponse response) {
log.debug(response.getStatusLine());
}
private void addHeaders(HttpRequestBase httpRequest, String content, String contentType) throws Exception {
String httpMethod = httpRequest.getMethod();
String path = httpRequest.getURI().getPath();
String contentMd5 = new Md5Digest().generate(content);
String nonce = "" + System.currentTimeMillis();
HashBasedMessageAuthenticationCode hmac = new HashBasedMessageAuthenticationCode(apiSecret);
HmacContent hmacContent = new HmacContent(httpMethod, path, contentMd5, contentType, nonce);
httpRequest.addHeader(HttpHeaders.AUTHORIZATION, new HmacAuthorizationHeader(apiKey, hmac.generate(hmacContent.toString())).format());
httpRequest.addHeader(HttpHeaders.NONCE, nonce);
httpRequest.addHeader(HttpHeaders.CONTENT_MD5, Base64.getEncoder().encodeToString(contentMd5.getBytes("UTF-8")));
httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
private void archiveWorkspace(long workspaceId, String json) {
if (this.workspaceArchiveLocation == null) {
return;
}
File archiveFile = new File(workspaceArchiveLocation, createArchiveFileName(workspaceId));
try {
FileWriter fileWriter = new FileWriter(archiveFile);
fileWriter.write(json);
fileWriter.flush();
fileWriter.close();
try {
log.debug("Workspace from server archived to " + archiveFile.getCanonicalPath());
} catch (IOException ioe) {
log.debug("Workspace from server archived to " + archiveFile.getAbsolutePath());
}
} catch (Exception e) {
log.warn("Could not archive JSON to " + archiveFile.getAbsolutePath());
}
}
private String createArchiveFileName(long workspaceId) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return "structurizr-" + workspaceId + "-" + sdf.format(new Date()) + ".json";
}
} | Added a simplified constructor.
| structurizr-client/src/com/structurizr/api/StructurizrClient.java | Added a simplified constructor. | <ide><path>tructurizr-client/src/com/structurizr/api/StructurizrClient.java
<ide> }
<ide>
<ide> /**
<add> * Creates a new Structurizr client with the specified API key and secret.
<add> */
<add> public StructurizrClient(String apiKey, String apiSecret) {
<add> setUrl("https://api.structurizr.com");
<add> this.apiKey = apiKey;
<add> this.apiSecret = apiSecret;
<add> }
<add>
<add> /**
<ide> * Creates a new Structurizr client with the specified API URL, key and secret.
<ide> */
<ide> public StructurizrClient(String url, String apiKey, String apiSecret) { |
|
Java | mit | 3ef068eef7584be75641a6b738bd10fb3078ea84 | 0 | Phoenix616/InventoryGui | package de.themoep.inventorygui;
/*
* Copyright 2017 Max Lee (https://github.com/Phoenix616)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.bukkit.inventory.ItemStack;
import java.util.function.Supplier;
/**
* Represents an element in a gui that will query all it's data when drawn.
*/
public class DynamicGuiElement extends GuiElement {
private Supplier<GuiElement> query;
private GuiElement cachedElement;
private long lastCached = 0;
/**
* Represents an element in a gui that will query all it's data when drawn.
* @param slotChar The character to replace in the gui setup string
* @param query Query the element data, this should return an element with the information
*/
public DynamicGuiElement(char slotChar, Supplier<GuiElement> query) {
super(slotChar);
this.query = query;
update();
}
/**
* Query this element's state even if it shouldn't be done yet
*/
public void update() {
lastCached = System.currentTimeMillis();
cachedElement = query.get();
cachedElement.setGui(gui);
}
@Override
public void setGui(InventoryGui gui) {
super.setGui(gui);
if (cachedElement != null) {
cachedElement.setGui(gui);
}
}
@Override
public ItemStack getItem(int slot) {
update();
return getCachedElement().getItem(slot);
}
@Override
public Action getAction() {
update();
return getCachedElement().getAction();
}
/**
* Get the supplier for this element's content
* @return The supplier query
*/
public Supplier<GuiElement> getQuery() {
return query;
}
/**
* Set the supplier for this element's content
* @param query The supplier query to set
*/
public void setQuery(Supplier<GuiElement> query) {
this.query = query;
}
/**
* Get the cached element, creates a new one if there is none
* @return The element that is currently cached
*/
public GuiElement getCachedElement() {
if (cachedElement == null) {
update();
}
return cachedElement;
}
/**
* Get the time at which this element was last cached
* @return The timestamp from when it was last cached
*/
public long getLastCached() {
return lastCached;
}
}
| src/main/java/de/themoep/inventorygui/DynamicGuiElement.java | package de.themoep.inventorygui;
/*
* Copyright 2017 Max Lee (https://github.com/Phoenix616)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.bukkit.inventory.ItemStack;
import java.util.function.Supplier;
/**
* Represents an element in a gui that will query all it's data when drawn.
*/
public class DynamicGuiElement extends GuiElement {
private Supplier<GuiElement> query;
private GuiElement cachedElement;
private long lastCached = 0;
private long cacheTime;
/**
* Represents an element in a gui that will query all it's data when drawn.
* @param slotChar The character to replace in the gui setup string
* @param query Query the element data, this should return an element with the information
* @param cacheTime The amounts of milliseconds that the element should stay cached and not query again
*/
public DynamicGuiElement(char slotChar, Supplier<GuiElement> query, long cacheTime) {
super(slotChar);
this.query = query;
this.cacheTime = cacheTime;
update(true);
}
/**
* Represents an element in a gui that will query all it's data when drawn. Stays cached for 10ms.
* @param slotChar The character to replace in the gui setup string
* @param query Query the element data, this should return an element with the information
*/
public DynamicGuiElement(char slotChar, Supplier<GuiElement> query) {
this(slotChar, query, 10);
}
/**
* Query this element's state even if it shouldn't be done yet
* @param force Whether or not to force an update even when the cache time hasn't been met yet
*/
public void update(boolean force) {
if (force || lastCached + cacheTime < System.currentTimeMillis()) {
lastCached = System.currentTimeMillis();
cachedElement = query.get();
cachedElement.setGui(gui);
}
}
@Override
public void setGui(InventoryGui gui) {
super.setGui(gui);
if (cachedElement != null) {
cachedElement.setGui(gui);
}
}
@Override
public ItemStack getItem(int slot) {
update(false);
if (cachedElement != null) {
return cachedElement.getItem(slot);
}
return null;
}
@Override
public Action getAction() {
update(false);
if (cachedElement != null) {
return cachedElement.getAction();
}
return null;
}
/**
* Get the supplier for this element's content
* @return The supplier query
*/
public Supplier<GuiElement> getQuery() {
return query;
}
/**
* Set the supplier for this element's content
* @param query The supplier query to set
*/
public void setQuery(Supplier<GuiElement> query) {
this.query = query;
}
/**
* Get the cached element
* @return The element that is currently cached
*/
public GuiElement getCachedElement() {
return cachedElement;
}
/**
* Set the time in which this element should stay cached and not update
* @param cacheTime The time in ms that it should stay cached
*/
public void setCacheTime(long cacheTime) {
this.cacheTime = cacheTime;
}
/**
* Get the time in which this element should stay cached and not update
* @return The time in ms that it should stay cached
*/
public long getCacheTime() {
return cacheTime;
}
}
| Get rid of the inbuilt caching of dynamic elements
That just leads to a very confusing behaviour when wanting to update the
element inside of a click action
| src/main/java/de/themoep/inventorygui/DynamicGuiElement.java | Get rid of the inbuilt caching of dynamic elements That just leads to a very confusing behaviour when wanting to update the element inside of a click action | <ide><path>rc/main/java/de/themoep/inventorygui/DynamicGuiElement.java
<ide> private Supplier<GuiElement> query;
<ide> private GuiElement cachedElement;
<ide> private long lastCached = 0;
<del> private long cacheTime;
<ide>
<ide> /**
<ide> * Represents an element in a gui that will query all it's data when drawn.
<ide> * @param slotChar The character to replace in the gui setup string
<ide> * @param query Query the element data, this should return an element with the information
<del> * @param cacheTime The amounts of milliseconds that the element should stay cached and not query again
<ide> */
<del> public DynamicGuiElement(char slotChar, Supplier<GuiElement> query, long cacheTime) {
<add> public DynamicGuiElement(char slotChar, Supplier<GuiElement> query) {
<ide> super(slotChar);
<ide> this.query = query;
<del> this.cacheTime = cacheTime;
<del> update(true);
<del> }
<del>
<del> /**
<del> * Represents an element in a gui that will query all it's data when drawn. Stays cached for 10ms.
<del> * @param slotChar The character to replace in the gui setup string
<del> * @param query Query the element data, this should return an element with the information
<del> */
<del> public DynamicGuiElement(char slotChar, Supplier<GuiElement> query) {
<del> this(slotChar, query, 10);
<add> update();
<ide> }
<ide>
<ide> /**
<ide> * Query this element's state even if it shouldn't be done yet
<del> * @param force Whether or not to force an update even when the cache time hasn't been met yet
<ide> */
<del> public void update(boolean force) {
<del> if (force || lastCached + cacheTime < System.currentTimeMillis()) {
<del> lastCached = System.currentTimeMillis();
<del> cachedElement = query.get();
<del> cachedElement.setGui(gui);
<del> }
<add> public void update() {
<add> lastCached = System.currentTimeMillis();
<add> cachedElement = query.get();
<add> cachedElement.setGui(gui);
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public ItemStack getItem(int slot) {
<del> update(false);
<del> if (cachedElement != null) {
<del> return cachedElement.getItem(slot);
<del> }
<del> return null;
<add> update();
<add> return getCachedElement().getItem(slot);
<ide> }
<ide>
<ide> @Override
<ide> public Action getAction() {
<del> update(false);
<del> if (cachedElement != null) {
<del> return cachedElement.getAction();
<del> }
<del> return null;
<add> update();
<add> return getCachedElement().getAction();
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<del> * Get the cached element
<add> * Get the cached element, creates a new one if there is none
<ide> * @return The element that is currently cached
<ide> */
<ide> public GuiElement getCachedElement() {
<add> if (cachedElement == null) {
<add> update();
<add> }
<ide> return cachedElement;
<ide> }
<ide>
<ide> /**
<del> * Set the time in which this element should stay cached and not update
<del> * @param cacheTime The time in ms that it should stay cached
<add> * Get the time at which this element was last cached
<add> * @return The timestamp from when it was last cached
<ide> */
<del> public void setCacheTime(long cacheTime) {
<del> this.cacheTime = cacheTime;
<del> }
<del>
<del> /**
<del> * Get the time in which this element should stay cached and not update
<del> * @return The time in ms that it should stay cached
<del> */
<del> public long getCacheTime() {
<del> return cacheTime;
<add> public long getLastCached() {
<add> return lastCached;
<ide> }
<ide> } |
|
Java | apache-2.0 | a2db48114832c2262713cb71b5646fe43377cc3f | 0 | davidmoten/rxjava2-extras,davidmoten/rxjava2-extras | package com.github.davidmoten.rx2.internal.flowable;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import com.github.davidmoten.rx2.Actions;
import com.github.davidmoten.rx2.Consumers;
import com.github.davidmoten.rx2.exceptions.ThrowingException;
import com.github.davidmoten.rx2.flowable.Transformers;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.Notification;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subscribers.TestSubscriber;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public final class FlowableRepeatingTransformTest {
private static final Function<List<Integer>, Integer> sum = (new Function<List<Integer>, Integer>() {
@Override
public Integer apply(List<Integer> list) throws Exception {
int sum = 0;
for (int value : list) {
sum += value;
}
return sum;
}
});
private static final Function<Flowable<Integer>, Flowable<Integer>> reducer = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.buffer(2).map(sum);
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> plusOne = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.map(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t) throws Exception {
return t + 1;
}
});
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrows = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
throw new ThrowingException();
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrowsOnThird = new Function<Flowable<Integer>, Flowable<Integer>>() {
final AtomicInteger count = new AtomicInteger();
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
if (count.incrementAndGet() >= 3) {
throw new ThrowingException();
} else {
return reducer.apply(f);
}
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerAsync = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.subscribeOn(Schedulers.computation()).buffer(2).map(sum);
}
};
@Test
public void testEmpty() {
int result = Flowable.<Integer>empty() //
.to(Transformers.reduce(reducer, 2)) //
.single(-1) //
.blockingGet();
Assert.assertEquals(-1, result);
}
@Test
public void testOne() {
check(1, 2);
}
@Test
public void testOneAsync() {
checkAsync(1, 2);
}
@Test
public void testCompletesFirstLevel() {
check(2, 2);
}
@Test
public void testCompletesSecondLevel() {
check(3, 2);
}
@Test(timeout = 1000)
public void testCompletesThirdLevel() {
check(4, 2);
}
@Test
public void testCompletesThirdLevelWithOneLeftOver() {
check(5, 2);
}
@Test
public void testCompletesFourLevels() {
check(8, 2);
}
@Test
public void testMany() {
for (int n = 5; n <= 100; n++) {
int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
System.out.println("maxChained=" + maxChained + ",n=" + n);
check(n, maxChained);
}
}
}
@Test
public void testManyAsync() {
for (int n = 5; n <= 100; n++) {
int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
System.out.println("maxChained=" + maxChained + ",n=" + n);
checkAsync(n, maxChained);
}
}
}
@Test(expected = IllegalArgumentException.class)
public void testMaxChainedGreaterThanZero() {
check(10, 0);
}
@Test
public void testReducerThrows() {
Flowable.range(1, 10) //
.to(Transformers.reduce(reducerThrows, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testReducerThrowsOnThirdCall() {
Flowable.range(1, 128) //
.to(Transformers.reduce(reducerThrowsOnThird, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testUpstreamCancelled() {
AtomicBoolean cancelled = new AtomicBoolean();
Flowable.<Integer>never() //
.doOnCancel(Actions.setToTrue(cancelled)) //
.to(Transformers.reduce(reducer, 2)) //
.test().cancel();
assertTrue(cancelled.get());
}
@Test
public void testErrorPreChaining() {
Flowable.<Integer>error(new ThrowingException()) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
@Ignore
public void testErrorPreChainingCausesCancel() {
AtomicBoolean cancelled = new AtomicBoolean();
Flowable.<Integer>error(new ThrowingException()) //
.doOnCancel(Actions.setToTrue(cancelled)) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
assertTrue(cancelled.get());
}
@Test
public void testErrorPostChaining() {
Flowable.range(1, 100) //
.concatWith(Flowable.<Integer>error(new ThrowingException())) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testMaxIterationsOne() {
Function<Observable<Integer>, Observable<?>> tester = new Function<Observable<Integer>, Observable<?>>() {
@Override
public Observable<?> apply(Observable<Integer> o) throws Exception {
return o.concatWith(Observable.<Integer>never());
}
};
Flowable.just(1, 5) //
.to(Transformers.repeat(plusOne, 3, 1, tester)) //
.doOnNext(Consumers.println()) //
.test() //
.assertValues(2, 6) //
.assertComplete();
}
@Test(timeout = 20000)
public void testMaxIterationsTwoMaxChainedThree() {
Flowable.just(1, 5) //
.to(Transformers.reduce(plusOne, 3, 2)) //
.test() //
.assertValues(3, 7) //
.assertComplete();
}
@Test(timeout = 20000)
public void testMaxIterations() {
Flowable.range(1, 2) //
.to(Transformers.reduce(plusOne, 2, 3)) //
.test() //
.assertValues(4, 5) //
.assertComplete();
}
@Test
public void testRequestOverflow() {
PublishSubject<Integer> subject = PublishSubject.create();
TestSubscriber<Integer> sub = subject.toFlowable(BackpressureStrategy.BUFFER) //
.to(Transformers.reduce(reducer, 2, 5)) //
.test(Long.MAX_VALUE - 2) //
.requestMore(Long.MAX_VALUE - 2);
subject.onNext(1);
subject.onNext(2);
subject.onComplete();
sub.assertValues(3);
}
@Test
public void testDematerialize() {
Flowable.just(Notification.createOnNext(1)).dematerialize().count().blockingGet();
Flowable.empty().dematerialize().count().blockingGet();
}
@Test
public void testBackpressure() {
Flowable.range(1, 4) //
.to(Transformers.reduce(plusOne, 2, 3)) //
.test(0) //
.assertNoValues() //
.requestMore(1) //
.assertValue(4) //
.requestMore(1) //
.assertValues(4, 5) //
.requestMore(2) //
.assertValues(4, 5, 6, 7) //
.assertComplete();
}
@Test
public void testBackpressureOnErrorNoRequests() {
Flowable.<Integer>error(new ThrowingException())//
.to(Transformers.reduce(plusOne, 2, 3)) //
.test(0) //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test(expected = IllegalArgumentException.class)
public void testMaxIterationsZeroThrowsIAE() {
@SuppressWarnings("unchecked")
Function<Observable<Integer>, Observable<?>> tester = Mockito.mock(Function.class);
Transformers.<Integer>repeat(plusOne, 2, 0, tester);
}
private static void check(int n, int maxChained) {
int result = Flowable.range(1, n) //
.to(Transformers.reduce(reducer, maxChained)) //
.doOnNext(Consumers.println()) //
.single(-1) //
.blockingGet();
Assert.assertEquals(sum(n), result);
}
private static void checkAsync(int n, int maxChained) {
int result = Flowable.range(1, n) //
.to(Transformers.reduce(reducerAsync, maxChained)) //
.single(-1) //
.blockingGet();
Assert.assertEquals(sum(n), result);
}
private static int sum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
}
| src/test/java/com/github/davidmoten/rx2/internal/flowable/FlowableRepeatingTransformTest.java | package com.github.davidmoten.rx2.internal.flowable;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import com.github.davidmoten.rx2.Actions;
import com.github.davidmoten.rx2.Consumers;
import com.github.davidmoten.rx2.Functions;
import com.github.davidmoten.rx2.exceptions.ThrowingException;
import com.github.davidmoten.rx2.flowable.Transformers;
import io.reactivex.Flowable;
import io.reactivex.Notification;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public final class FlowableRepeatingTransformTest {
private static final Function<List<Integer>, Integer> sum = (new Function<List<Integer>, Integer>() {
@Override
public Integer apply(List<Integer> list) throws Exception {
int sum = 0;
for (int value : list) {
sum += value;
}
return sum;
}
});
private static final Function<Flowable<Integer>, Flowable<Integer>> reducer = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.buffer(2).map(sum);
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> plusOne = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.map(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t) throws Exception {
return t + 1;
}
});
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrows = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
throw new ThrowingException();
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrowsOnThird = new Function<Flowable<Integer>, Flowable<Integer>>() {
final AtomicInteger count = new AtomicInteger();
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
if (count.incrementAndGet() >= 3) {
throw new ThrowingException();
} else {
return reducer.apply(f);
}
}
};
private static final Function<Flowable<Integer>, Flowable<Integer>> reducerAsync = new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
return f.subscribeOn(Schedulers.computation()).buffer(2).map(sum);
}
};
@Test
public void testEmpty() {
int result = Flowable.<Integer>empty() //
.to(Transformers.reduce(reducer, 2)) //
.single(-1) //
.blockingGet();
Assert.assertEquals(-1, result);
}
@Test
public void testOne() {
check(1, 2);
}
@Test
public void testOneAsync() {
checkAsync(1, 2);
}
@Test
public void testCompletesFirstLevel() {
check(2, 2);
}
@Test
public void testCompletesSecondLevel() {
check(3, 2);
}
@Test(timeout = 1000)
public void testCompletesThirdLevel() {
check(4, 2);
}
@Test
public void testCompletesThirdLevelWithOneLeftOver() {
check(5, 2);
}
@Test
public void testCompletesFourLevels() {
check(8, 2);
}
@Test
public void testMany() {
for (int n = 5; n <= 100; n++) {
int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
System.out.println("maxChained=" + maxChained + ",n=" + n);
check(n, maxChained);
}
}
}
@Test
public void testManyAsync() {
for (int n = 5; n <= 100; n++) {
int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
System.out.println("maxChained=" + maxChained + ",n=" + n);
checkAsync(n, maxChained);
}
}
}
@Test(expected = IllegalArgumentException.class)
public void testMaxChainedGreaterThanZero() {
check(10, 0);
}
@Test
public void testReducerThrows() {
Flowable.range(1, 10) //
.to(Transformers.reduce(reducerThrows, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testReducerThrowsOnThirdCall() {
Flowable.range(1, 128) //
.to(Transformers.reduce(reducerThrowsOnThird, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testUpstreamCancelled() {
AtomicBoolean cancelled = new AtomicBoolean();
Flowable.<Integer>never() //
.doOnCancel(Actions.setToTrue(cancelled)) //
.to(Transformers.reduce(reducer, 2)) //
.test().cancel();
assertTrue(cancelled.get());
}
@Test
public void testErrorPreChaining() {
Flowable.<Integer>error(new ThrowingException()) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
@Ignore
public void testErrorPreChainingCausesCancel() {
AtomicBoolean cancelled = new AtomicBoolean();
Flowable.<Integer>error(new ThrowingException()) //
.doOnCancel(Actions.setToTrue(cancelled)) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
assertTrue(cancelled.get());
}
@Test
public void testErrorPostChaining() {
Flowable.range(1, 100) //
.concatWith(Flowable.<Integer>error(new ThrowingException())) //
.to(Transformers.reduce(reducer, 2)) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test
public void testMaxIterationsOne() {
Function<Observable<Integer>, Observable<?>> tester = new Function<Observable<Integer>, Observable<?>>() {
@Override
public Observable<?> apply(Observable<Integer> o) throws Exception {
return o.concatWith(Observable.<Integer>never());
}
};
Flowable.just(1, 5) //
.to(Transformers.repeat(plusOne, 3, 1, tester)) //
.doOnNext(Consumers.println()) //
.test() //
.assertValues(2, 6) //
.assertComplete();
}
@Test(timeout = 20000)
public void testMaxIterationsTwoMaxChainedThree() {
Flowable.just(1, 5) //
.to(Transformers.reduce(plusOne, 3, 2)) //
.test() //
.assertValues(3, 7) //
.assertComplete();
}
@Test(timeout = 20000)
public void testMaxIterations() {
Flowable.range(1, 2) //
.to(Transformers.reduce(plusOne, 2, 3)) //
.test() //
.assertValues(4, 5) //
.assertComplete();
}
@Test
public void testDematerialize() {
Flowable.just(Notification.createOnNext(1)).dematerialize().count().blockingGet();
Flowable.empty().dematerialize().count().blockingGet();
}
@Test
public void testBackpressure() {
Flowable.range(1, 4) //
.to(Transformers.reduce(plusOne, 2, 3)) //
.test(0) //
.assertNoValues() //
.requestMore(1) //
.assertValue(4) //
.requestMore(1) //
.assertValues(4, 5) //
.requestMore(2) //
.assertValues(4, 5, 6, 7) //
.assertComplete();
}
@Test
public void testBackpressureOnErrorNoRequests() {
Flowable.<Integer>error(new ThrowingException())//
.to(Transformers.reduce(plusOne, 2, 3)) //
.test(0) //
.assertNoValues() //
.assertError(ThrowingException.class);
}
@Test(expected=IllegalArgumentException.class)
public void testMaxIterationsZeroThrowsIAE() {
@SuppressWarnings("unchecked")
Function<Observable<Integer>, Observable<?>> tester = Mockito.mock(Function.class);
Transformers.<Integer>repeat(plusOne, 2, 0, tester);
}
private static void check(int n, int maxChained) {
int result = Flowable.range(1, n) //
.to(Transformers.reduce(reducer, maxChained)) //
.doOnNext(Consumers.println()) //
.single(-1) //
.blockingGet();
Assert.assertEquals(sum(n), result);
}
private static void checkAsync(int n, int maxChained) {
int result = Flowable.range(1, n) //
.to(Transformers.reduce(reducerAsync, maxChained)) //
.single(-1) //
.blockingGet();
Assert.assertEquals(sum(n), result);
}
private static int sum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
}
| repeatingTransform - add test
| src/test/java/com/github/davidmoten/rx2/internal/flowable/FlowableRepeatingTransformTest.java | repeatingTransform - add test | <ide><path>rc/test/java/com/github/davidmoten/rx2/internal/flowable/FlowableRepeatingTransformTest.java
<ide>
<ide> import com.github.davidmoten.rx2.Actions;
<ide> import com.github.davidmoten.rx2.Consumers;
<del>import com.github.davidmoten.rx2.Functions;
<ide> import com.github.davidmoten.rx2.exceptions.ThrowingException;
<ide> import com.github.davidmoten.rx2.flowable.Transformers;
<ide>
<add>import io.reactivex.BackpressureStrategy;
<ide> import io.reactivex.Flowable;
<ide> import io.reactivex.Notification;
<ide> import io.reactivex.Observable;
<ide> import io.reactivex.functions.Function;
<ide> import io.reactivex.schedulers.Schedulers;
<add>import io.reactivex.subjects.PublishSubject;
<add>import io.reactivex.subscribers.TestSubscriber;
<ide>
<ide> @FixMethodOrder(MethodSorters.NAME_ASCENDING)
<ide> public final class FlowableRepeatingTransformTest {
<ide> .test() //
<ide> .assertValues(4, 5) //
<ide> .assertComplete();
<add> }
<add>
<add> @Test
<add> public void testRequestOverflow() {
<add> PublishSubject<Integer> subject = PublishSubject.create();
<add>
<add> TestSubscriber<Integer> sub = subject.toFlowable(BackpressureStrategy.BUFFER) //
<add> .to(Transformers.reduce(reducer, 2, 5)) //
<add> .test(Long.MAX_VALUE - 2) //
<add> .requestMore(Long.MAX_VALUE - 2);
<add> subject.onNext(1);
<add> subject.onNext(2);
<add> subject.onComplete();
<add> sub.assertValues(3);
<ide> }
<ide>
<ide> @Test
<ide> .assertError(ThrowingException.class);
<ide> }
<ide>
<del> @Test(expected=IllegalArgumentException.class)
<add> @Test(expected = IllegalArgumentException.class)
<ide> public void testMaxIterationsZeroThrowsIAE() {
<ide> @SuppressWarnings("unchecked")
<ide> Function<Observable<Integer>, Observable<?>> tester = Mockito.mock(Function.class); |
|
Java | apache-2.0 | 84f62a5cff462eaa3bfaf171b0638c7e7feea30d | 0 | mosoft521/wicket,apache/wicket,mosoft521/wicket,apache/wicket,mosoft521/wicket,mosoft521/wicket,apache/wicket,apache/wicket,apache/wicket,mosoft521/wicket | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.protocol.http.request;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.core.request.ClientInfo;
import org.apache.wicket.markup.html.pages.BrowserInfoPage;
import org.apache.wicket.protocol.http.ClientProperties;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.string.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default client info object for web applications.
*
* @author Eelco Hillenius
*/
public class WebClientInfo extends ClientInfo
{
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(WebClientInfo.class);
/**
* The user agent string from the User-Agent header, app. Theoretically, this might differ from
* {@link org.apache.wicket.protocol.http.ClientProperties#isNavigatorJavaEnabled()} property, which is
* not set until an actual reply from a browser (e.g. using {@link BrowserInfoPage} is set.
*/
private final String userAgent;
/** Client properties object. */
private final ClientProperties properties;
/**
* Construct.
*
* @param requestCycle
* the request cycle
*/
public WebClientInfo(RequestCycle requestCycle)
{
this(requestCycle, new ClientProperties());
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
*/
public WebClientInfo(RequestCycle requestCycle, ClientProperties properties)
{
this(requestCycle, ((ServletWebRequest)requestCycle.getRequest()).getContainerRequest()
.getHeader("User-Agent"), properties);
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
* @param userAgent
* The User-Agent string
*/
public WebClientInfo(final RequestCycle requestCycle, final String userAgent)
{
this(requestCycle, userAgent, new ClientProperties());
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
* @param userAgent
* The User-Agent string
* @param properties
* properties of client
*/
public WebClientInfo(final RequestCycle requestCycle, final String userAgent, final ClientProperties properties)
{
super();
this.userAgent = userAgent;
this.properties = properties;
properties.setRemoteAddress(getRemoteAddr(requestCycle));
}
/**
* Gets the client properties object.
*
* @return the client properties object
*/
public final ClientProperties getProperties()
{
return properties;
}
/**
* returns the user agent string.
*
* @return the user agent string
*/
public final String getUserAgent()
{
return userAgent;
}
/**
* returns the user agent string (lower case).
*
* @return the user agent string
*/
private String getUserAgentStringLc()
{
return (getUserAgent() != null) ? getUserAgent().toLowerCase(Locale.ROOT) : "";
}
/**
* Returns the IP address from {@code HttpServletRequest.getRemoteAddr()}.
*
* @param requestCycle
* the request cycle
* @return remoteAddr IP address of the client, using
* {@code getHttpServletRequest().getRemoteAddr()}
*/
protected String getRemoteAddr(RequestCycle requestCycle)
{
ServletWebRequest request = (ServletWebRequest)requestCycle.getRequest();
return request.getContainerRequest().getRemoteAddr();
}
}
| wicket-core/src/main/java/org/apache/wicket/protocol/http/request/WebClientInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.protocol.http.request;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.core.request.ClientInfo;
import org.apache.wicket.markup.html.pages.BrowserInfoPage;
import org.apache.wicket.protocol.http.ClientProperties;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.string.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default client info object for web applications.
*
* @author Eelco Hillenius
*/
public class WebClientInfo extends ClientInfo
{
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(WebClientInfo.class);
/**
* The user agent string from the User-Agent header, app. Theoretically, this might differ from
* {@link org.apache.wicket.protocol.http.ClientProperties#isNavigatorJavaEnabled()} property, which is
* not set until an actual reply from a browser (e.g. using {@link BrowserInfoPage} is set.
*/
private final String userAgent;
/** Client properties object. */
private final ClientProperties properties;
/**
* Construct.
*
* @param requestCycle
* the request cycle
*/
public WebClientInfo(RequestCycle requestCycle)
{
this(requestCycle, new ClientProperties());
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
*/
public WebClientInfo(RequestCycle requestCycle, ClientProperties properties)
{
this(requestCycle, ((ServletWebRequest)requestCycle.getRequest()).getContainerRequest()
.getHeader("User-Agent"), properties);
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
* @param userAgent
* The User-Agent string
*/
public WebClientInfo(final RequestCycle requestCycle, final String userAgent)
{
this(requestCycle, userAgent, new ClientProperties());
}
/**
* Construct.
*
* @param requestCycle
* the request cycle
* @param userAgent
* The User-Agent string
* @param properties
* properties of client
*/
public WebClientInfo(final RequestCycle requestCycle, final String userAgent, final ClientProperties properties)
{
super();
this.userAgent = userAgent;
this.properties = properties;
properties.setRemoteAddress(getRemoteAddr(requestCycle));
}
/**
* Gets the client properties object.
*
* @return the client properties object
*/
public final ClientProperties getProperties()
{
return properties;
}
/**
* returns the user agent string.
*
* @return the user agent string
*/
public final String getUserAgent()
{
return userAgent;
}
/**
* returns the user agent string (lower case).
*
* @return the user agent string
*/
private String getUserAgentStringLc()
{
return (getUserAgent() != null) ? getUserAgent().toLowerCase(Locale.ROOT) : "";
}
/**
* When using ProxyPass, requestCycle().getHttpServletRequest(). getRemoteAddr() returns the IP
* of the machine forwarding the request. In order to maintain the clients ip address, the
* server places it in the <a
* href="http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#x-headers">X-Forwarded-For</a>
* Header.
*
* Proxies may also mask the original client IP with tokens like "hidden" or "unknown".
* If so, the last proxy ip address is returned.
*
* @param requestCycle
* the request cycle
* @return remoteAddr IP address of the client, using the X-Forwarded-For header and defaulting
* to: getHttpServletRequest().getRemoteAddr()
*/
protected String getRemoteAddr(RequestCycle requestCycle)
{
ServletWebRequest request = (ServletWebRequest)requestCycle.getRequest();
HttpServletRequest req = request.getContainerRequest();
String remoteAddr = request.getHeader("X-Forwarded-For");
if (remoteAddr != null)
{
if (remoteAddr.contains(","))
{
// sometimes the header is of form client ip,proxy 1 ip,proxy 2 ip,...,proxy n ip,
// we just want the client
remoteAddr = Strings.split(remoteAddr, ',')[0].trim();
}
try
{
// If ip4/6 address string handed over, simply does pattern validation.
InetAddress.getByName(remoteAddr);
}
catch (UnknownHostException e)
{
remoteAddr = req.getRemoteAddr();
}
}
else
{
remoteAddr = req.getRemoteAddr();
}
return remoteAddr;
}
}
| Do not try to resolve X-Forwarded-For header
The remote address is reported by HttpServletRequest. Configuration of
this property is normally done via the application server. If this is
somehow not possible, use XForwardedRequestWrapperFactory.
| wicket-core/src/main/java/org/apache/wicket/protocol/http/request/WebClientInfo.java | Do not try to resolve X-Forwarded-For header | <ide><path>icket-core/src/main/java/org/apache/wicket/protocol/http/request/WebClientInfo.java
<ide> }
<ide>
<ide> /**
<del> * When using ProxyPass, requestCycle().getHttpServletRequest(). getRemoteAddr() returns the IP
<del> * of the machine forwarding the request. In order to maintain the clients ip address, the
<del> * server places it in the <a
<del> * href="http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#x-headers">X-Forwarded-For</a>
<del> * Header.
<del> *
<del> * Proxies may also mask the original client IP with tokens like "hidden" or "unknown".
<del> * If so, the last proxy ip address is returned.
<add> * Returns the IP address from {@code HttpServletRequest.getRemoteAddr()}.
<ide> *
<ide> * @param requestCycle
<ide> * the request cycle
<del> * @return remoteAddr IP address of the client, using the X-Forwarded-For header and defaulting
<del> * to: getHttpServletRequest().getRemoteAddr()
<add> * @return remoteAddr IP address of the client, using
<add> * {@code getHttpServletRequest().getRemoteAddr()}
<ide> */
<ide> protected String getRemoteAddr(RequestCycle requestCycle)
<ide> {
<ide> ServletWebRequest request = (ServletWebRequest)requestCycle.getRequest();
<del> HttpServletRequest req = request.getContainerRequest();
<del> String remoteAddr = request.getHeader("X-Forwarded-For");
<del>
<del> if (remoteAddr != null)
<del> {
<del> if (remoteAddr.contains(","))
<del> {
<del> // sometimes the header is of form client ip,proxy 1 ip,proxy 2 ip,...,proxy n ip,
<del> // we just want the client
<del> remoteAddr = Strings.split(remoteAddr, ',')[0].trim();
<del> }
<del> try
<del> {
<del> // If ip4/6 address string handed over, simply does pattern validation.
<del> InetAddress.getByName(remoteAddr);
<del> }
<del> catch (UnknownHostException e)
<del> {
<del> remoteAddr = req.getRemoteAddr();
<del> }
<del> }
<del> else
<del> {
<del> remoteAddr = req.getRemoteAddr();
<del> }
<del> return remoteAddr;
<add> return request.getContainerRequest().getRemoteAddr();
<ide> }
<ide> } |
|
JavaScript | mit | ddffb00fd717543e0d804918130c295de6884b68 | 0 | blockstack/blockstack-site,blockstack/blockstack-site | 'use strict'
import {Component} from 'react'
import {Link} from 'react-router'
import DocumentTitle from 'react-document-title'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {BlogActions} from '../datastore/Blog'
import {StatsActions} from '../datastore/Stats'
import Image from '../components/Image'
import Header from '../components/Header'
import Alert from '../components/Alert'
import EmbedYouTube from '../components/EmbedYouTube'
import MultiVideoPlayer from '../components/MultiVideoPlayer'
import PostPreview from '../components/PostPreview'
import {featuredApps} from '../config'
function mapStateToProps(state) {
return {
posts: state.blog.posts,
stats: state.stats,
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
Object.assign({}, BlogActions, StatsActions),
dispatch
)
}
class HomePage extends Component {
constructor(props) {
super(props)
this.state = {
videos: [
{
src: 'https://www.youtube.com/embed/Z4bMFKBRg_k',
previewImageUrl: '/images/resources/video-home-1-preview.jpg',
thumbnailImageUrl: '/images/resources/video-home-1-thumbnail.jpg',
},
{
src: 'https://www.youtube.com/embed/qtOIh93Hvuw',
previewImageUrl: '/images/resources/video-home-2-thumbnail.jpg',
thumbnailImageUrl: '/images/resources/video-home-2-thumbnail.jpg',
},
{
src: 'https://www.youtube.com/embed/YzlyEuRfXxo',
previewImageUrl: '/images/resources/video-home-3-thumbnail.jpg',
thumbnailImageUrl: '/images/resources/video-home-3-thumbnail.jpg',
}
],
stats: this.props.stats,
posts: this.props.posts
}
}
componentWillMount() {
if (this.props.posts.length === 0) {
this.props.fetchPosts()
}
this.props.fetchStats()
}
componentWillReceiveProps(nextProps) {
if (nextProps.stats !== this.props.stats) {
let stats = nextProps.stats
if (stats.domains === 0) {
stats.domains = 72000
}
this.setState({
stats: stats,
})
}
if (nextProps.posts !== this.props.posts) {
this.setState({
posts: nextProps.posts,
})
}
}
render() {
const firstThreePosts = this.state.posts.slice(0, 3)
const content = {
fullStack: [
{
title: 'Identity',
body: 'With Blockstack, users get digital keys that let them own their identity. They sign in to apps locally without remote servers or identity providers.'
},
{
title: 'Storage',
body: 'Blockstack\'s storage system allows users to bring their own storage providers and control their data. Data is encrypted and easily shared between applications.'
},
{
title: 'Tokens',
body: 'Blockstack uses Bitcoin and other crypto-currencies for simple peer-to-peer payments. Developers can charge for downloads, subscriptions, and more.'
},
],
appPossibilities: [
{
title: 'Decentralized Social Networks',
body: 'Existing social networks lock in users and limit access. Build a decentralized social network that allows users to own their relationships and data and take it with them wherever they go.'
},
{
title: 'Peer-to-peer Marketplaces',
body: 'Existing marketplaces take a massive haircut and limit what can be bought and sold. Build a peer-to-peer marketplace that allows individuals to freely transact at a lower cost.'
},
{
title: 'Collaborative Search Engines',
body: 'The web was built to be open and accessible but today the search indexes we rely upon are proprietary. Build a platform that incentivizes people to contribute to a collaborative index.'
}
]
}
return (
<DocumentTitle title="Blockstack, building the decentralized internet">
<div className="body-hero">
<div className="w-100" style={{ overflow: 'hidden' }}>
<div>
<Header transparent={true} />
<div className="container">
<section className="hero text-center">
<h1 className="text-white m-b-20">
A New Internet for Decentralized Apps
</h1>
<p className="hero-lead purple-50 col-md-9 col-centered">
Blockstack is a new internet for decentralized apps where users own their data.<br/>A browser is all that’s needed to get started.
</p>
<div className="no-padding container-fluid col-md-10 col-lg-10 col-centered m-b-55">
<div className="row">
<div className="col-sm-12 col-md-4 mx-auto">
<p className="">
<Link to="/install" role="button"
className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
Install
</Link>
</p>
</div>
</div>
</div>
<div className="no-padding container-fluid col-md-9 col-centered">
<div className="text-center d-none d-sm-block">
<Image className="landing-feat-img"
src="/images/resources/[email protected]"
fallbackSrc="/images/resources/browser-home-screen.png"
retinaSupport={false} />
</div>
<div className="caption-browser d-none d-sm-block">
Blockstack Browser
</div>
</div>
</section>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-secondary section-stats">
<div className="container">
<div className="row">
<div className="col-sm-4 text-center text-stats text-white">
{this.state.stats.domains.toLocaleString()}
<span className="text-stats-description text-white">domains registered</span>
</div>
<div className="col-sm-4 text-center text-stats text-white">
3+
<span className="text-stats-description text-white">years in production</span>
</div>
<div className="col-sm-4 text-center text-stats text-white">
{this.state.stats.meetupUsers.toLocaleString()}
<span className="text-stats-description text-white">community devs</span>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="col-sm-12">
<MultiVideoPlayer videos={this.state.videos}/>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container container-lg sectionWrap">
<div className="row">
<div className="col-md-3 text-center m-b-25">
<a href="https://blockstack.org/whitepaper.pdf" target="_blank">
<Image className="col-img icon-lg-special"
src="/images/icons/[email protected]"
retinaSupport={false} />
</a>
</div>
<div className="col-md-9 m-b-25">
<div className="container">
<h3 className="text-center text-white">
The Blockstack Whitepaper
</h3>
<a href="https://blockstack.org/whitepaper.pdf" role="button"
className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
Download Whitepaper
</a>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-25">
A Full Stack for Decentralized Apps
</h2>
</div>
<div className="col-sm-12 text-center landing-hero-img m-b-35">
<Image className="landing-feat-img container-sm"
src="/images/visuals/blockstack-architecture-diagram.svg"
retinaSupport={false} />
</div>
<div className="container-fluid">
<div className="row">
{content.fullStack.map((item, index) => {
return (
<div key={index} className="col-lg-4 m-b-25">
<h4 className="inverse text-center">
{item.title}
</h4>
<p className="inverse text-center">
{item.body}
</p>
</div>
)
})}
</div>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-light-gray">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-25">
Libraries and Step-by-Step Tutorials
</h2>
</div>
<div className="container m-b-30">
<div className="col-md-8 col-centered">
<p className="text-center">
Complete the step-by-step tutorial and see how easy it is to build an app with a decentralized identity system in a few lines of code and no servers.
</p>
</div>
</div>
<div className="container m-b-80">
<div className="row">
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Identity
</h4>
<p className="light-gray text-center">
Available today!
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-identity.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Storage
</h4>
<p className="light-gray text-center">
Available today!
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-storage.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Tokens
</h4>
<p className="light-gray text-center">
<i>Coming Soon...</i>
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-payments.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
</div>
</div>
<div className="container container-xs">
<p className="text-center">
<Link to="/tutorials" role="button"
className="btn btn-primary btn-block">
Try the Tutorials
</Link>
</p>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-85">
Featured Apps on Blockstack
</h2>
</div>
<div className="container-fluid">
{[[0,3], [3,5]].map((row, index) => {
return (
<div key={index} className="row">
{featuredApps.slice(row[0],row[1]).map((featuredApp, index2) => {
const offsetClass = (row[0] === 3 && index2 === 0) ? '' : ''
return (
<div key={index2}
className={`col-lg-4 m-b-55 mx-auto ${offsetClass}`}>
<p className="text-center">
<Image className="col-img" src={featuredApp.icon}
retinaSupport={false} />
</p>
<h4 className="modern text-center">
{featuredApp.name}
</h4>
<p className="text-center">
{featuredApp.description}
</p>
</div>
)
})}
</div>
)
})}
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-light-gray">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<div className="row">
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="https://www.wsj.com/articles/blockstack-launches-25-million-fund-for-blockchain-startups-1502883001" target="_blank">
<h4 className="text-center">
<Image className="h-press-wsj"
src="/images/logos/wsj-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“Blockstack… has launched a $25 million fund to invest in startups that build on its technology.”
</p>
</a>
</div>
</div>
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="http://observer.com/2016/09/a-second-internet-coming-soon-courtesy-of-the-blockchain/" target="_blank">
<h4 className="text-center">
<Image className="h-press-observer"
src="/images/logos/observer-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“Blockstack… has been designing an alternative browser for what could be fairly described as another internet”
</p>
</a>
</div>
</div>
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="https://www.technologyreview.com/s/603352/one-startups-vision-to-reinvent-the-web-for-better-privacy/" target="_blank">
<h4 className="text-center">
<Image className="h-press-mit"
src="/images/logos/mit-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“A kind of parallel universe to the Web we know — one where users have more control of their data.”
</p>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-primary text-white">
<div className="row">
<div className="col-sm-10 col-lg-11 col-xl-12 mx-auto m-b-80 m-t-35">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-35">
Get Started
</h2>
</div>
<div className="col-12 col-xl-8 container-lg mx-auto">
<div className="row">
<div className="col-md-6 m-b-20">
<Link to="/install" role="button"
className="btn btn-primary btn-block m-b-10">
Install
</Link>
</div>
<div className="col-md-6 m-b-20">
<Link to="/signup" role="button"
className="btn btn-primary btn-block">
Get Updates
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</DocumentTitle>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
| app/js/pages/HomePage.js | 'use strict'
import {Component} from 'react'
import {Link} from 'react-router'
import DocumentTitle from 'react-document-title'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {BlogActions} from '../datastore/Blog'
import {StatsActions} from '../datastore/Stats'
import Image from '../components/Image'
import Header from '../components/Header'
import Alert from '../components/Alert'
import EmbedYouTube from '../components/EmbedYouTube'
import MultiVideoPlayer from '../components/MultiVideoPlayer'
import PostPreview from '../components/PostPreview'
import {featuredApps} from '../config'
function mapStateToProps(state) {
return {
posts: state.blog.posts,
stats: state.stats,
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
Object.assign({}, BlogActions, StatsActions),
dispatch
)
}
class HomePage extends Component {
constructor(props) {
super(props)
this.state = {
videos: [
{
src: 'https://www.youtube.com/embed/Z4bMFKBRg_k',
previewImageUrl: '/images/resources/video-home-1-preview.jpg',
thumbnailImageUrl: '/images/resources/video-home-1-thumbnail.jpg',
},
{
src: 'https://www.youtube.com/embed/qtOIh93Hvuw',
previewImageUrl: '/images/resources/video-home-2-thumbnail.jpg',
thumbnailImageUrl: '/images/resources/video-home-2-thumbnail.jpg',
},
{
src: 'https://www.youtube.com/embed/YzlyEuRfXxo',
previewImageUrl: '/images/resources/video-home-3-thumbnail.jpg',
thumbnailImageUrl: '/images/resources/video-home-3-thumbnail.jpg',
}
],
stats: this.props.stats,
posts: this.props.posts
}
}
componentWillMount() {
if (this.props.posts.length === 0) {
this.props.fetchPosts()
}
this.props.fetchStats()
}
componentWillReceiveProps(nextProps) {
if (nextProps.stats !== this.props.stats) {
let stats = nextProps.stats
if (stats.domains === 0) {
stats.domains = 72000
}
this.setState({
stats: stats,
})
}
if (nextProps.posts !== this.props.posts) {
this.setState({
posts: nextProps.posts,
})
}
}
render() {
const firstThreePosts = this.state.posts.slice(0, 3)
const content = {
fullStack: [
{
title: 'Identity',
body: 'With Blockstack, users get digital keys that let them own their identity. They sign in to apps locally without remote servers or identity providers.'
},
{
title: 'Storage',
body: 'Blockstack\'s storage system allows users to bring their own storage providers and control their data. Data is encrypted and easily shared between applications.'
},
{
title: 'Tokens',
body: 'Blockstack uses Bitcoin and other crypto-currencies for simple peer-to-peer payments. Developers can charge for downloads, subscriptions, and more.'
},
],
appPossibilities: [
{
title: 'Decentralized Social Networks',
body: 'Existing social networks lock in users and limit access. Build a decentralized social network that allows users to own their relationships and data and take it with them wherever they go.'
},
{
title: 'Peer-to-peer Marketplaces',
body: 'Existing marketplaces take a massive haircut and limit what can be bought and sold. Build a peer-to-peer marketplace that allows individuals to freely transact at a lower cost.'
},
{
title: 'Collaborative Search Engines',
body: 'The web was built to be open and accessible but today the search indexes we rely upon are proprietary. Build a platform that incentivizes people to contribute to a collaborative index.'
}
]
}
return (
<DocumentTitle title="Blockstack, building the decentralized internet">
<div className="body-hero">
<div className="w-100" style={{ overflow: 'hidden' }}>
<div>
<Header transparent={true} />
<div className="container">
<section className="hero text-center">
<h1 className="text-white m-b-20">
A New Internet for Decentralized Apps
</h1>
<p className="hero-lead purple-50 col-md-9 col-centered">
Blockstack is a new internet for decentralized apps where users own their data.<br/>A browser is all that’s needed to get started.
</p>
<div className="no-padding container-fluid col-md-10 col-lg-10 col-centered m-b-95">
<div className="row">
<div className="col-sm-12 col-md-6">
<p className="float-md-right">
<Link to="/install" role="button"
className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
Install
</Link>
</p>
</div>
<div className="col-sm-12 col-md-6">
<p className="float-md-left">
<Link to="/signup" role="button"
className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
Get Updates
</Link>
</p>
</div>
</div>
</div>
<div className="no-padding container-fluid col-md-9 col-centered">
<div className="text-center d-none d-sm-block">
<Image className="landing-feat-img"
src="/images/resources/[email protected]"
fallbackSrc="/images/resources/browser-home-screen.png"
retinaSupport={false} />
</div>
<div className="caption-browser d-none d-sm-block">
Blockstack Browser
</div>
</div>
</section>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-secondary section-stats">
<div className="container">
<div className="row">
<div className="col-sm-4 text-center text-stats text-white">
{this.state.stats.domains.toLocaleString()}
<span className="text-stats-description text-white">domains registered</span>
</div>
<div className="col-sm-4 text-center text-stats text-white">
3+
<span className="text-stats-description text-white">years in production</span>
</div>
<div className="col-sm-4 text-center text-stats text-white">
{this.state.stats.meetupUsers.toLocaleString()}
<span className="text-stats-description text-white">community devs</span>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="col-sm-12">
<MultiVideoPlayer videos={this.state.videos}/>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container container-lg sectionWrap">
<div className="row">
<div className="col-md-3 text-center m-b-25">
<a href="https://blockstack.org/whitepaper.pdf" target="_blank">
<Image className="col-img icon-lg-special"
src="/images/icons/[email protected]"
retinaSupport={false} />
</a>
</div>
<div className="col-md-9 m-b-25">
<div className="container">
<h3 className="text-center text-white">
The Blockstack Whitepaper
</h3>
<a href="https://blockstack.org/whitepaper.pdf" role="button"
className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
Download Whitepaper
</a>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-25">
A Full Stack for Decentralized Apps
</h2>
</div>
<div className="col-sm-12 text-center landing-hero-img m-b-35">
<Image className="landing-feat-img container-sm"
src="/images/visuals/blockstack-architecture-diagram.svg"
retinaSupport={false} />
</div>
<div className="container-fluid">
<div className="row">
{content.fullStack.map((item, index) => {
return (
<div key={index} className="col-lg-4 m-b-25">
<h4 className="inverse text-center">
{item.title}
</h4>
<p className="inverse text-center">
{item.body}
</p>
</div>
)
})}
</div>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-light-gray">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-25">
Libraries and Step-by-Step Tutorials
</h2>
</div>
<div className="container m-b-30">
<div className="col-md-8 col-centered">
<p className="text-center">
Complete the step-by-step tutorial and see how easy it is to build an app with a decentralized identity system in a few lines of code and no servers.
</p>
</div>
</div>
<div className="container m-b-80">
<div className="row">
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Identity
</h4>
<p className="light-gray text-center">
Available today!
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-identity.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Storage
</h4>
<p className="light-gray text-center">
Available today!
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-storage.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
<div className="col-xl-4 code-img-gutter">
<h4 className="text-center m-b-10">
Tokens
</h4>
<p className="light-gray text-center">
<i>Coming Soon...</i>
</p>
<p className="text-center">
<Image className="col3-img-lg"
src="/images/visuals/text-editor-payments.svg"
fallbackSrc=""
retinaSupport={false} />
</p>
</div>
</div>
</div>
<div className="container container-xs">
<p className="text-center">
<Link to="/tutorials" role="button"
className="btn btn-primary btn-block">
Try the Tutorials
</Link>
</p>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-white">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-85">
Featured Apps on Blockstack
</h2>
</div>
<div className="container-fluid">
{[[0,3], [3,5]].map((row, index) => {
return (
<div key={index} className="row">
{featuredApps.slice(row[0],row[1]).map((featuredApp, index2) => {
const offsetClass = (row[0] === 3 && index2 === 0) ? '' : ''
return (
<div key={index2}
className={`col-lg-4 m-b-55 mx-auto ${offsetClass}`}>
<p className="text-center">
<Image className="col-img" src={featuredApp.icon}
retinaSupport={false} />
</p>
<h4 className="modern text-center">
{featuredApp.name}
</h4>
<p className="text-center">
{featuredApp.description}
</p>
</div>
)
})}
</div>
)
})}
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-light-gray">
<div className="row">
<div className="container">
<div className="row">
<div className="container-fluid">
<div className="row">
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="https://www.wsj.com/articles/blockstack-launches-25-million-fund-for-blockchain-startups-1502883001" target="_blank">
<h4 className="text-center">
<Image className="h-press-wsj"
src="/images/logos/wsj-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“Blockstack… has launched a $25 million fund to invest in startups that build on its technology.”
</p>
</a>
</div>
</div>
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="http://observer.com/2016/09/a-second-internet-coming-soon-courtesy-of-the-blockchain/" target="_blank">
<h4 className="text-center">
<Image className="h-press-observer"
src="/images/logos/observer-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“Blockstack… has been designing an alternative browser for what could be fairly described as another internet”
</p>
</a>
</div>
</div>
<div className="col-lg-4 m-b-25">
<div className="container">
<a href="https://www.technologyreview.com/s/603352/one-startups-vision-to-reinvent-the-web-for-better-privacy/" target="_blank">
<h4 className="text-center">
<Image className="h-press-mit"
src="/images/logos/mit-logo-BW-40.svg"
retinaSupport={false} />
</h4>
<p className="font-weight-bold text-center">
“A kind of parallel universe to the Web we know — one where users have more control of their data.”
</p>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{/* New section layout applied */}
<div className="container-fluid sectionWrap bg-primary text-white">
<div className="row">
<div className="col-sm-10 col-lg-11 col-xl-12 mx-auto m-b-80 m-t-35">
<div className="row">
<div className="container-fluid">
<h2 className="text-center m-b-35">
Get Started
</h2>
</div>
<div className="col-12 col-xl-8 container-lg mx-auto">
<div className="row">
<div className="col-md-6 m-b-20">
<Link to="/install" role="button"
className="btn btn-primary btn-block m-b-10">
Install
</Link>
</div>
<div className="col-md-6 m-b-20">
<Link to="/signup" role="button"
className="btn btn-primary btn-block">
Get Updates
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</DocumentTitle>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
| removed get updates btn #436
| app/js/pages/HomePage.js | removed get updates btn #436 | <ide><path>pp/js/pages/HomePage.js
<ide> <p className="hero-lead purple-50 col-md-9 col-centered">
<ide> Blockstack is a new internet for decentralized apps where users own their data.<br/>A browser is all that’s needed to get started.
<ide> </p>
<del> <div className="no-padding container-fluid col-md-10 col-lg-10 col-centered m-b-95">
<add> <div className="no-padding container-fluid col-md-10 col-lg-10 col-centered m-b-55">
<ide> <div className="row">
<del> <div className="col-sm-12 col-md-6">
<del> <p className="float-md-right">
<add> <div className="col-sm-12 col-md-4 mx-auto">
<add> <p className="">
<ide> <Link to="/install" role="button"
<ide> className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
<ide> Install
<del> </Link>
<del> </p>
<del> </div>
<del> <div className="col-sm-12 col-md-6">
<del> <p className="float-md-left">
<del> <Link to="/signup" role="button"
<del> className="btn btn-primary btn-block btn-block-reset" style={{ minWidth: '245px' }}>
<del> Get Updates
<ide> </Link>
<ide> </p>
<ide> </div> |
|
Java | apache-2.0 | c47ef459d54124bedd10b3a9636b115076c61675 | 0 | msgilligan/jsr354-ri,miyakawataku/jsr354-ri,miyakawataku/jsr354-ri,msgilligan/jsr354-ri | /*
* Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil. Licensed under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License. Contributors: Anatole Tresch - initial implementation Wernner Keil - extensions and
* adaptions.
*/
package org.javamoney.moneta.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Locale;
import javax.money.MonetaryAmounts;
import javax.money.MonetaryCurrencies;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.junit.Test;
/**
* @author Anatole
*
*/
public class MonetaryAmountFormatTest {
/**
* Test method for {@link javax.money.format.MonetaryAmountFormat#getAmountStyle()} .
*/
@Test
public void testGetAmountStyle() {
}
/**
* Test method for {@link javax.money.format.MonetaryAmountFormat#getDefaultCurrency()} .
*/
@Test
public void testGetDefaultCurrency() {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
Locale.GERMANY);
assertNull(defaultFormat.getDefaultCurrency());
defaultFormat = new MonetaryFormats.Builder(Locale.GERMANY).with(
MonetaryCurrencies.getCurrency("CHF")).create();
assertEquals(MonetaryCurrencies.getCurrency("CHF"),
defaultFormat.getDefaultCurrency());
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#format(javax.money.MonetaryAmount)} .
*/
@Test
public void testFormat() {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
Locale.GERMANY);
assertEquals(
"CHF 12,50"
,
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"CHF").with(12.50).create()));
assertEquals(
"INR 123.456.789.101.112,12",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"INR").with(
123456789101112.123456).create()));
defaultFormat = MonetaryFormats.getDefaultFormat(new Locale("", "IN"));
assertEquals(
"CHF 1,211,112.50",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"CHF").with(
1211112.50).create()));
assertEquals(
"INR 123,456,789,101,112.12",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"INR").with(
123456789101112.123456).create()));
// Locale india = new Locale("", "IN");
// defaultFormat = MonetaryFormats.getAmountFormatBuilder(india)
// .setNumberGroupSizes(3, 2).build();
// assertEquals("INR 12,34,56,78,91,01,112.12",
// defaultFormat.format(MonetaryAmounts.getAmount("INR",
// 123456789101112.123456)));
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#print(java.lang.Appendable, javax.money.MonetaryAmount)}
* .
*
* @throws IOException
*/
@Test
public void testPrint() throws IOException {
StringBuilder b = new StringBuilder();
MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
Locale.GERMANY);
defaultFormat.print(
b,
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
12.50).create());
assertEquals("CHF 12,50", b.toString());
b.setLength(0);
defaultFormat.print(b, MonetaryAmounts.getDefaultAmountFactory()
.withCurrency("INR").with(123456789101112.123456).create());
assertEquals("INR 123.456.789.101.112,12",
b.toString());
b.setLength(0);
defaultFormat = MonetaryFormats.getDefaultFormat(new Locale("", "IN"));
defaultFormat.print(
b,
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
1211112.50).create());
assertEquals("CHF 1,211,112.50",
b.toString());
b.setLength(0);
defaultFormat.print(b, MonetaryAmounts.getDefaultAmountFactory()
.withCurrency("INR").with(
123456789101112.123456).create());
assertEquals("INR 123,456,789,101,112.12",
b.toString());
b.setLength(0);
// Locale india = new Locale("", "IN");
// defaultFormat = MonetaryFormats.getAmountFormat(india)
// .setNumberGroupSizes(3, 2).build();
// defaultFormat.print(b, MonetaryAmounts.getAmount("INR",
// 123456789101112.123456));
// assertEquals("INR 12,34,56,78,91,01,112.12",
// b.toString());
}
/**
* Test method for {@link javax.money.format.MonetaryAmountFormat#parse(java.lang.CharSequence)}
* .
*
* @throws ParseException
*/
@Test
public void testParse() throws ParseException {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
Locale.GERMANY);
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse("EUR 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse(" \t EUR 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse(" \t EUR \t\n\r 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse("CHF 12,50"));
// defaultFormat = MonetaryFormats
// .getAmountFormatBuilder(new Locale("", "IN"))
// .setNumberGroupSizes(3, 2).build();
// assertEquals(MonetaryAmounts.getAmount("INR", new BigDecimal(
// "123456789101112.12")),
// defaultFormat.parse("INR 12,34,56,78,91,01,112.12"));
}
}
| src/test/java/org/javamoney/moneta/format/MonetaryAmountFormatTest.java | /*
* Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Contributors: Anatole Tresch - initial implementation Wernner Keil -
* extensions and adaptions.
*/
package org.javamoney.moneta.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Locale;
import javax.money.MonetaryAmounts;
import javax.money.MonetaryCurrencies;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.junit.Test;
/**
* @author Anatole
*
*/
public class MonetaryAmountFormatTest {
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#getAmountStyle()} .
*/
@Test
public void testGetAmountStyle() {
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#getDefaultCurrency()} .
*/
@Test
public void testGetDefaultCurrency() {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
Locale.GERMANY);
assertNull(defaultFormat.getDefaultCurrency());
defaultFormat = MonetaryFormats.getAmountFormat(
Locale.GERMANY, MonetaryCurrencies.getCurrency("CHF"));
assertEquals(MonetaryCurrencies.getCurrency("CHF"),
defaultFormat.getDefaultCurrency());
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#format(javax.money.MonetaryAmount)}
* .
*/
@Test
public void testFormat() {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
Locale.GERMANY);
assertEquals(
"CHF 12,50"
,
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"CHF").with(12.50).create()));
assertEquals(
"INR 123.456.789.101.112,12",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"INR").with(
123456789101112.123456).create()));
defaultFormat = MonetaryFormats.getAmountFormat(new Locale("", "IN"));
assertEquals(
"CHF 1,211,112.50",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"CHF").with(
1211112.50).create()));
assertEquals(
"INR 123,456,789,101,112.12",
defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
.withCurrency(
"INR").with(
123456789101112.123456).create()));
// Locale india = new Locale("", "IN");
// defaultFormat = MonetaryFormats.getAmountFormatBuilder(india)
// .setNumberGroupSizes(3, 2).build();
// assertEquals("INR 12,34,56,78,91,01,112.12",
// defaultFormat.format(MonetaryAmounts.getAmount("INR",
// 123456789101112.123456)));
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#print(java.lang.Appendable, javax.money.MonetaryAmount)}
* .
*
* @throws IOException
*/
@Test
public void testPrint() throws IOException {
StringBuilder b = new StringBuilder();
MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
Locale.GERMANY);
defaultFormat.print(
b,
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
12.50).create());
assertEquals("CHF 12,50", b.toString());
b.setLength(0);
defaultFormat.print(b, MonetaryAmounts.getDefaultAmountFactory()
.withCurrency("INR").with(123456789101112.123456).create());
assertEquals("INR 123.456.789.101.112,12",
b.toString());
b.setLength(0);
defaultFormat = MonetaryFormats.getAmountFormat(new Locale("", "IN"));
defaultFormat.print(
b,
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
1211112.50).create());
assertEquals("CHF 1,211,112.50",
b.toString());
b.setLength(0);
defaultFormat.print(b, MonetaryAmounts.getDefaultAmountFactory()
.withCurrency("INR").with(
123456789101112.123456).create());
assertEquals("INR 123,456,789,101,112.12",
b.toString());
b.setLength(0);
// Locale india = new Locale("", "IN");
// defaultFormat = MonetaryFormats.getAmountFormat(india)
// .setNumberGroupSizes(3, 2).build();
// defaultFormat.print(b, MonetaryAmounts.getAmount("INR",
// 123456789101112.123456));
// assertEquals("INR 12,34,56,78,91,01,112.12",
// b.toString());
}
/**
* Test method for
* {@link javax.money.format.MonetaryAmountFormat#parse(java.lang.CharSequence)}
* .
*
* @throws ParseException
*/
@Test
public void testParse() throws ParseException {
MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
Locale.GERMANY);
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse("EUR 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse(" \t EUR 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse(" \t EUR \t\n\r 12,50"));
assertEquals(
MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
.with(
new BigDecimal("12.50")).create(),
defaultFormat.parse("CHF 12,50"));
// defaultFormat = MonetaryFormats
// .getAmountFormatBuilder(new Locale("", "IN"))
// .setNumberGroupSizes(3, 2).build();
// assertEquals(MonetaryAmounts.getAmount("INR", new BigDecimal(
// "123456789101112.12")),
// defaultFormat.parse("INR 12,34,56,78,91,01,112.12"));
}
}
| Reworked MonetaryFormats. | src/test/java/org/javamoney/moneta/format/MonetaryAmountFormatTest.java | Reworked MonetaryFormats. | <ide><path>rc/test/java/org/javamoney/moneta/format/MonetaryAmountFormatTest.java
<ide> /*
<del> * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not
<del> * use this file except in compliance with the License. You may obtain a copy of
<del> * the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<del> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
<del> * License for the specific language governing permissions and limitations under
<del> * the License.
<del> *
<del> * Contributors: Anatole Tresch - initial implementation Wernner Keil -
<del> * extensions and adaptions.
<add> * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil. Licensed under the Apache
<add> * License, Version 2.0 (the "License"); you may not use this file except in compliance with the
<add> * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License
<add> * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
<add> * or implied. See the License for the specific language governing permissions and limitations under
<add> * the License. Contributors: Anatole Tresch - initial implementation Wernner Keil - extensions and
<add> * adaptions.
<ide> */
<ide> package org.javamoney.moneta.format;
<ide>
<ide> public class MonetaryAmountFormatTest {
<ide>
<ide> /**
<del> * Test method for
<del> * {@link javax.money.format.MonetaryAmountFormat#getAmountStyle()} .
<add> * Test method for {@link javax.money.format.MonetaryAmountFormat#getAmountStyle()} .
<ide> */
<ide> @Test
<ide> public void testGetAmountStyle() {
<ide> }
<ide>
<ide> /**
<del> * Test method for
<del> * {@link javax.money.format.MonetaryAmountFormat#getDefaultCurrency()} .
<add> * Test method for {@link javax.money.format.MonetaryAmountFormat#getDefaultCurrency()} .
<ide> */
<ide> @Test
<ide> public void testGetDefaultCurrency() {
<del> MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
<add> MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
<ide> Locale.GERMANY);
<ide> assertNull(defaultFormat.getDefaultCurrency());
<del> defaultFormat = MonetaryFormats.getAmountFormat(
<del> Locale.GERMANY, MonetaryCurrencies.getCurrency("CHF"));
<add> defaultFormat = new MonetaryFormats.Builder(Locale.GERMANY).with(
<add> MonetaryCurrencies.getCurrency("CHF")).create();
<ide> assertEquals(MonetaryCurrencies.getCurrency("CHF"),
<ide> defaultFormat.getDefaultCurrency());
<ide> }
<ide>
<ide> /**
<ide> * Test method for
<del> * {@link javax.money.format.MonetaryAmountFormat#format(javax.money.MonetaryAmount)}
<del> * .
<add> * {@link javax.money.format.MonetaryAmountFormat#format(javax.money.MonetaryAmount)} .
<ide> */
<ide> @Test
<ide> public void testFormat() {
<del> MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
<add> MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
<ide> Locale.GERMANY);
<ide> assertEquals(
<ide> "CHF 12,50"
<ide> .withCurrency(
<ide> "INR").with(
<ide> 123456789101112.123456).create()));
<del> defaultFormat = MonetaryFormats.getAmountFormat(new Locale("", "IN"));
<add> defaultFormat = MonetaryFormats.getDefaultFormat(new Locale("", "IN"));
<ide> assertEquals(
<ide> "CHF 1,211,112.50",
<ide> defaultFormat.format(MonetaryAmounts.getDefaultAmountFactory()
<ide> @Test
<ide> public void testPrint() throws IOException {
<ide> StringBuilder b = new StringBuilder();
<del> MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
<add> MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
<ide> Locale.GERMANY);
<ide> defaultFormat.print(
<ide> b,
<ide> assertEquals("INR 123.456.789.101.112,12",
<ide> b.toString());
<ide> b.setLength(0);
<del> defaultFormat = MonetaryFormats.getAmountFormat(new Locale("", "IN"));
<add> defaultFormat = MonetaryFormats.getDefaultFormat(new Locale("", "IN"));
<ide> defaultFormat.print(
<ide> b,
<ide> MonetaryAmounts.getDefaultAmountFactory().withCurrency("CHF")
<ide> }
<ide>
<ide> /**
<del> * Test method for
<del> * {@link javax.money.format.MonetaryAmountFormat#parse(java.lang.CharSequence)}
<add> * Test method for {@link javax.money.format.MonetaryAmountFormat#parse(java.lang.CharSequence)}
<ide> * .
<ide> *
<ide> * @throws ParseException
<ide> */
<ide> @Test
<ide> public void testParse() throws ParseException {
<del> MonetaryAmountFormat defaultFormat = MonetaryFormats.getAmountFormat(
<add> MonetaryAmountFormat defaultFormat = MonetaryFormats.getDefaultFormat(
<ide> Locale.GERMANY);
<ide> assertEquals(
<ide> MonetaryAmounts.getDefaultAmountFactory().withCurrency("EUR") |
|
JavaScript | apache-2.0 | e34f0c05779d23d49701e30fe11806634baa5463 | 0 | gitterHQ/cordova-js,revolunet/cordova-js,lvrookie/cordova-js,danrixd/cordova-js,yedeveloper/cordova-js,Adilmar/cordova-js,Adilmar/cordova-js,the1sky/cordova-js,infil00p/cordova-js,Zekom/cordova-js,corimf/cordova-js,yedeveloper/cordova-js,Adilmar/cordova-js,andfaulkner/cordovajs-cms-one,andfaulkner/cordovajs-cms-one,danrixd/cordova-js,Zekom/cordova-js,Zekom/cordova-js,the1sky/cordova-js,danrixd/cordova-js,lvrookie/cordova-js,gitterHQ/cordova-js,corimf/cordova-js,the1sky/cordova-js,apache/cordova-js,corimf/cordova-js,revolunet/cordova-js,infil00p/cordova-js,lvrookie/cordova-js,revolunet/cordova-js,yedeveloper/cordova-js,andfaulkner/cordovajs-cms-one |
var cordova = require('cordova'),
exec = require('cordova/exec'),
channel = cordova.require("cordova/channel");
module.exports = {
id: "windows8",
initialize:function() {
},
objects: {
navigator: {
children: {
device: {
path:"cordova/plugin/windows8/device",
children:{
capture:{
path:"cordova/plugin/capture"
}
}
},
console: {
path: "cordova/plugin/windows8/console"
}
}
}
},
merges: {
Entry: {
path: 'cordova/plugin/windows8/Entry'
},
MediaFile: {
path: "cordova/plugin/windows8/MediaFile"
},
navigator: {
children: {
geolocation: {
path: 'cordova/plugin/windows8/geolocation'
}
}
}
}
};
| lib/windows8/platform.js |
var cordova = require('cordova'),
exec = require('cordova/exec'),
channel = cordova.require("cordova/channel");
module.exports = {
id: "windows8",
initialize:function() {
},
objects: {
navigator: {
children: {
device: {
path:"cordova/plugin/windows8/device",
children:{
capture:{
path:"cordova/plugin/capture"
}
}
},
console: {
path: "cordova/plugin/windows8/console"
}
}
}
},
merges: {
Entry: {
path: 'cordova/plugin/windows8/Entry'
},
MediaFile: {
path: "cordova/plugin/windows8/MediaFile"
},
navigator: {
children: {
notification: {
path: 'cordova/plugin/windows8/geolocation'
}
}
}
}
};
| Fixed error in a previous commit
| lib/windows8/platform.js | Fixed error in a previous commit | <ide><path>ib/windows8/platform.js
<ide> },
<ide> navigator: {
<ide> children: {
<del> notification: {
<add> geolocation: {
<ide> path: 'cordova/plugin/windows8/geolocation'
<ide> }
<ide> } |
|
Java | apache-2.0 | 065ec5ad85d0ddf5618a7512fa2f00089a7ba39d | 0 | spolti/arquillian-cube,mikesir87/arquillian-cube,AndyGee/arquillian-cube,spolti/arquillian-cube,mikesir87/arquillian-cube,AndyGee/arquillian-cube,AndyGee/arquillian-cube,lordofthejars/arquillian-cube,lordofthejars/arquillian-cube,mikesir87/arquillian-cube,lordofthejars/arquillian-cube,spolti/arquillian-cube | package org.arquillian.cube.docker.impl.util;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.arquillian.cube.docker.impl.docker.DockerClientExecutor;
public final class Ping {
public static final String COMMAND_NOT_FOUND = "command not found";
private Ping() {
super();
}
public static boolean ping(DockerClientExecutor dockerClientExecutor, String containerId, String command, int totalIterations, long sleep, TimeUnit timeUnit) {
boolean result = false;
int iteration = 0;
do {
result = execContainerPing(dockerClientExecutor, containerId, command);
if(!result) {
iteration++;
try {
timeUnit.sleep(sleep);
} catch (InterruptedException e) {
}
}
} while(!result && iteration < totalIterations);
return result;
}
public static boolean ping(String host, int port, int totalIterations, long sleep, TimeUnit timeUnit) {
boolean result = false;
int iteration = 0;
do {
result = ping(host, port);
if(!result) {
iteration++;
try {
timeUnit.sleep(sleep);
} catch (InterruptedException e) {
}
}
} while(!result && iteration < totalIterations);
return result;
}
private static boolean execContainerPing(DockerClientExecutor dockerClientExecutor, String containerId, String command) {
final String[] commands = {"sh", "-c", command};
String result = dockerClientExecutor.execStart(containerId, commands);
if (result == null) {
throw new IllegalArgumentException(
String.format("Command %s in container %s has returned no value.", Arrays.toString(commands), containerId));
}
if (result != null && result.contains(COMMAND_NOT_FOUND)) {
throw new UnsupportedOperationException(
String.format("Command %s is not available in container %s.", Arrays.toString(commands), containerId));
}
try {
int numberOfListenConnectons = Integer.parseInt(result.trim());
//This number is based in that a port will be opened only as tcp or as udp.
//We will need another issue to modify cube internals to save if port is udp or tcp.
return numberOfListenConnectons > 0;
} catch(NumberFormatException e) {
return false;
}
}
private static boolean ping(String host, int port) {
Socket socket = null;
try {
socket = new Socket(host, port);
return true;
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
} finally {
if (socket != null) try { socket.close(); } catch(IOException e) {}
}
}
}
| docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/Ping.java | package org.arquillian.cube.docker.impl.util;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import org.arquillian.cube.docker.impl.docker.DockerClientExecutor;
public final class Ping {
private Ping() {
super();
}
public static boolean ping(DockerClientExecutor dockerClientExecutor, String containerId, String command, int totalIterations, long sleep, TimeUnit timeUnit) {
boolean result = false;
int iteration = 0;
do {
result = execContainerPing(dockerClientExecutor, containerId, command);
if(!result) {
iteration++;
try {
timeUnit.sleep(sleep);
} catch (InterruptedException e) {
}
}
} while(!result && iteration < totalIterations);
return result;
}
public static boolean ping(String host, int port, int totalIterations, long sleep, TimeUnit timeUnit) {
boolean result = false;
int iteration = 0;
do {
result = ping(host, port);
if(!result) {
iteration++;
try {
timeUnit.sleep(sleep);
} catch (InterruptedException e) {
}
}
} while(!result && iteration < totalIterations);
return result;
}
private static boolean execContainerPing(DockerClientExecutor dockerClientExecutor, String containerId, String command) {
String result = dockerClientExecutor.execStart(containerId, new String[]{"sh", "-c", command});
try {
int numberOfListenConnectons = Integer.parseInt(result.trim());
//This number is based in that a port will be opened only as tcp or as udp.
//We will need another issue to modify cube internals to save if port is udp or tcp.
return numberOfListenConnectons > 0;
} catch(NumberFormatException e) {
return false;
}
}
private static boolean ping(String host, int port) {
Socket socket = null;
try {
socket = new Socket(host, port);
return true;
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
} finally {
if (socket != null) try { socket.close(); } catch(IOException e) {}
}
}
}
| adds checks for detecting when ping(ss) command is not installed on container.
| docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/Ping.java | adds checks for detecting when ping(ss) command is not installed on container. | <ide><path>ocker/docker/src/main/java/org/arquillian/cube/docker/impl/util/Ping.java
<ide> import java.io.IOException;
<ide> import java.net.Socket;
<ide> import java.net.UnknownHostException;
<add>import java.util.Arrays;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.arquillian.cube.docker.impl.docker.DockerClientExecutor;
<ide>
<ide> public final class Ping {
<add>
<add> public static final String COMMAND_NOT_FOUND = "command not found";
<ide>
<ide> private Ping() {
<ide> super();
<ide>
<ide>
<ide> private static boolean execContainerPing(DockerClientExecutor dockerClientExecutor, String containerId, String command) {
<del> String result = dockerClientExecutor.execStart(containerId, new String[]{"sh", "-c", command});
<add>
<add> final String[] commands = {"sh", "-c", command};
<add> String result = dockerClientExecutor.execStart(containerId, commands);
<add>
<add> if (result == null) {
<add> throw new IllegalArgumentException(
<add> String.format("Command %s in container %s has returned no value.", Arrays.toString(commands), containerId));
<add> }
<add>
<add> if (result != null && result.contains(COMMAND_NOT_FOUND)) {
<add> throw new UnsupportedOperationException(
<add> String.format("Command %s is not available in container %s.", Arrays.toString(commands), containerId));
<add> }
<add>
<ide> try {
<ide> int numberOfListenConnectons = Integer.parseInt(result.trim());
<ide> //This number is based in that a port will be opened only as tcp or as udp. |
|
JavaScript | agpl-3.0 | 41bbf9d7657272bc2557c72afe5bcf8a30eff3a9 | 0 | petrjasek/superdesk-ntb,verifiedpixel/superdesk,liveblog/superdesk,vied12/superdesk,superdesk/superdesk,mdhaman/superdesk,sivakuna-aap/superdesk,sivakuna-aap/superdesk,liveblog/superdesk,mdhaman/superdesk-aap,superdesk/superdesk-aap,petrjasek/superdesk-ntb,plamut/superdesk,ioanpocol/superdesk,pavlovicnemanja/superdesk,pavlovicnemanja/superdesk,superdesk/superdesk-ntb,hlmnrmr/superdesk,pavlovicnemanja92/superdesk,darconny/superdesk,thnkloud9/superdesk,fritzSF/superdesk,fritzSF/superdesk,plamut/superdesk,ancafarcas/superdesk,amagdas/superdesk,ancafarcas/superdesk,sivakuna-aap/superdesk,pavlovicnemanja/superdesk,ioanpocol/superdesk-ntb,pavlovicnemanja92/superdesk,superdesk/superdesk-aap,ancafarcas/superdesk,sjunaid/superdesk,verifiedpixel/superdesk,mugurrus/superdesk,vied12/superdesk,mdhaman/superdesk,marwoodandrew/superdesk-aap,liveblog/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,superdesk/superdesk-ntb,ioanpocol/superdesk,sjunaid/superdesk,akintolga/superdesk-aap,Aca-jov/superdesk,marwoodandrew/superdesk-aap,vied12/superdesk,sivakuna-aap/superdesk,superdesk/superdesk-aap,darconny/superdesk,hlmnrmr/superdesk,akintolga/superdesk,pavlovicnemanja/superdesk,thnkloud9/superdesk,plamut/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,petrjasek/superdesk-ntb,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,marwoodandrew/superdesk,darconny/superdesk,amagdas/superdesk,liveblog/superdesk,gbbr/superdesk,superdesk/superdesk-ntb,petrjasek/superdesk,fritzSF/superdesk,petrjasek/superdesk,hlmnrmr/superdesk,gbbr/superdesk,Aca-jov/superdesk,petrjasek/superdesk,pavlovicnemanja92/superdesk,fritzSF/superdesk,verifiedpixel/superdesk,marwoodandrew/superdesk-aap,plamut/superdesk,gbbr/superdesk,Aca-jov/superdesk,superdesk/superdesk-aap,liveblog/superdesk,mugurrus/superdesk,mugurrus/superdesk,superdesk/superdesk,fritzSF/superdesk,petrjasek/superdesk,marwoodandrew/superdesk,superdesk/superdesk-ntb,superdesk/superdesk,mdhaman/superdesk,sjunaid/superdesk,pavlovicnemanja92/superdesk,amagdas/superdesk,amagdas/superdesk,ioanpocol/superdesk,marwoodandrew/superdesk,marwoodandrew/superdesk,vied12/superdesk,mdhaman/superdesk-aap,verifiedpixel/superdesk,vied12/superdesk,akintolga/superdesk-aap,thnkloud9/superdesk,plamut/superdesk,ioanpocol/superdesk-ntb,superdesk/superdesk,akintolga/superdesk-aap,akintolga/superdesk,petrjasek/superdesk-ntb,mdhaman/superdesk-aap,amagdas/superdesk,akintolga/superdesk,verifiedpixel/superdesk,marwoodandrew/superdesk-aap,akintolga/superdesk-aap,akintolga/superdesk | define([
'lodash',
'angular',
'require'
], function(_, angular, require) {
'use strict';
return angular.module('superdesk.archive.directives', [])
.directive('sdInlineMeta', function() {
return {
templateUrl: require.toUrl('./views/inline-meta.html'),
scope: {
'placeholder': '@',
'showmeta': '=',
'item': '=',
'setmeta': '&'
}
};
})
.directive('sdMediaPreview', ['api', function(api) {
return {
replace: true,
templateUrl: require.toUrl('./views/preview.html'),
scope: {item: '='},
link: function(scope, elem) {
scope.$watch('item', function(item) {
scope.contents = null;
if (item.type === 'composite') {
scope.contents = [];
var mainPackage = _.find(item.groups, {id: 'main'});
_.each(mainPackage.refs, function(r) {
api.ingest.getById(r.residRef)
.then(function(_item) {
var t = _item.type;
if (_.find(scope.contents, {type: t}) === undefined) {
scope.contents.push({type: t, items: [_item]});
} else {
scope.contents[_.findIndex(scope.contents, {type: t})].items.push(_item);
}
}, function(response) {
if (response.status === 404) {
console.log('Item not found');
}
});
});
}
});
}
};
}])
.directive('sdMediaView', ['keyboardManager', 'api', function(keyboardManager, api) {
return {
replace: true,
templateUrl: require.toUrl('./views/media-view.html'),
scope: {
items: '=',
item: '='
},
link: function(scope, elem) {
scope.singleItem = null;
scope.packageContents = null;
scope.prevEnabled = true;
scope.nextEnabled = true;
var getIndex = function(item) {
return _.findIndex(scope.items, item);
};
var setItem = function(item) {
scope.item = item;
scope.setSingleItem(item);
var index = getIndex(scope.item);
scope.prevEnabled = !!scope.items[index - 1];
scope.nextEnabled = !!scope.items[index + 1];
};
scope.prev = function() {
var index = getIndex(scope.item);
if (index > 0) {
setItem(scope.items[index - 1]);
}
};
scope.next = function() {
var index = getIndex(scope.item);
if (index !== -1 && index < scope.items.length - 1) {
setItem(scope.items[index + 1]);
}
};
keyboardManager.push('left', scope.prev);
keyboardManager.push('right', scope.next);
scope.$on('$destroy', function() {
keyboardManager.pop('left');
keyboardManager.pop('right');
});
scope.setSingleItem = function(item) {
scope.singleItem = item;
if (scope.singleItem !== null) {
if (scope.singleItem.type === 'composite') {
scope.packageContents = [];
var mainPackage = _.find(scope.singleItem.groups, {id: 'main'});
_.each(mainPackage.refs, function(r) {
api.ingest.getById(r.residRef)
.then(function(item) {
scope.packageContents.push(item);
}, function(response) {
if (response.status === 404) {
console.log('Item not found');
}
});
});
}
}
};
setItem(scope.item);
}
};
}])
.directive('sdSingleItem', [ function() {
return {
replace: true,
templateUrl: require.toUrl('./views/single-item-preview.html'),
scope: {
item: '=',
contents: '='
},
link: function(scope, elem) {
}
};
}])
.directive('sdSidebarLayout', ['$location', '$filter', function($location, $filter) {
return {
transclude: true,
templateUrl: require.toUrl('./views/sidebar.html')
};
}])
.directive('sdMediaBox', function() {
return {
restrict: 'A',
templateUrl: require.toUrl('./views/media-box.html'),
link: function(scope, element, attrs) {
if (!scope.activityFilter && scope.extras) {
scope.activityFilter = scope.extras.activityFilter;
}
scope.$watch('extras.view', function(view) {
switch (view) {
case 'mlist':
case 'compact':
scope.itemTemplate = require.toUrl('./views/media-box-list.html');
break;
default:
scope.itemTemplate = require.toUrl('./views/media-box-grid.html');
}
});
}
};
})
.directive('sdItemRendition', function() {
return {
templateUrl: require.toUrl('./views/item-rendition.html'),
scope: {item: '=', rendition: '@'},
link: function(scope, elem) {
scope.$watch('item.renditions[rendition].href', function(href) {
var figure = elem.find('figure'),
oldImg = figure.find('img').css('opacity', 0.5);
if (href) {
var img = new Image();
img.onload = function() {
if (oldImg.length) {
oldImg.replaceWith(img);
} else {
figure.prepend(img);
}
};
img.src = href;
}
});
}
};
})
.directive('sdHtmlPreview', ['$sce', function($sce) {
return {
scope: {sdHtmlPreview: '='},
template: '<div ng-bind-html="html"></div>',
link: function(scope, elem, attrs) {
scope.$watch('sdHtmlPreview', function(html) {
scope.html = $sce.trustAsHtml(html);
});
}
};
}])
.directive('sdProviderMenu', ['$location', function($location) {
return {
scope: {items: '='},
templateUrl: require.toUrl('./views/provider-menu.html'),
link: function(scope, element, attrs) {
scope.setProvider = function(provider) {
scope.selected = provider;
$location.search('provider', scope.selected);
};
scope.$watchCollection(function() {
return $location.search();
}, function(search) {
if (search.provider) {
scope.selected = search.provider;
}
});
}
};
}])
.directive('sdToggleBox', function() {
return {
templateUrl: require.toUrl('./views/toggleBox.html'),
replace: true,
transclude: true,
scope: true,
link: function($scope, element, attrs) {
$scope.title = attrs.title;
$scope.isOpen = attrs.open === 'true';
$scope.icon = attrs.icon;
$scope.toggleModule = function() {
$scope.isOpen = !$scope.isOpen;
};
}
};
})
.directive('sdFilterUrgency', ['$location', function($location) {
return {
scope: true,
link: function($scope, element, attrs) {
$scope.urgency = {
min: $location.search().urgency_min || 1,
max: $location.search().urgency_max || 5
};
function handleUrgency(urgency) {
var min = Math.round(urgency.min);
var max = Math.round(urgency.max);
if (min !== 1 || max !== 5) {
var urgency_norm = {
min: min,
max: max
};
$location.search('urgency_min', urgency_norm.min);
$location.search('urgency_max', urgency_norm.max);
} else {
$location.search('urgency_min', null);
$location.search('urgency_max', null);
}
}
var handleUrgencyWrap = _.throttle(handleUrgency, 2000);
$scope.$watchCollection('urgency', function(newVal) {
handleUrgencyWrap(newVal);
});
}
};
}])
.directive('sdFilterContenttype', [ '$location', function($location) {
return {
restrict: 'A',
templateUrl: require.toUrl('./views/filter-contenttype.html'),
replace: true,
scope: {
items: '='
},
link: function(scope, element, attrs) {
scope.contenttype = [
{
term: 'text',
checked: false,
count: 0
},
{
term: 'audio',
checked: false,
count: 0
},
{
term: 'video',
checked: false,
count: 0
},
{
term: 'picture',
checked: false,
count: 0
},
{
term: 'graphic',
checked: false,
count: 0
},
{
term: 'composite',
checked: false,
count: 0
}
];
var search = $location.search();
if (search.type) {
var type = JSON.parse(search.type);
_.forEach(type, function(term) {
_.extend(_.first(_.where(scope.contenttype, {term: term})), {checked: true});
});
}
scope.$watchCollection('items', function() {
if (scope.items && scope.items._facets !== undefined) {
_.forEach(scope.items._facets.type.terms, function(type) {
_.extend(_.first(_.where(scope.contenttype, {term: type.term})), type);
});
}
});
scope.setContenttypeFilter = function() {
var contenttype = _.map(_.where(scope.contenttype, {'checked': true}), function(t) {
return t.term;
});
if (contenttype.length === 0) {
$location.search('type', null);
} else {
$location.search('type', JSON.stringify(contenttype));
}
};
}
};
}])
.directive('sdGridLayout', function() {
return {
templateUrl: 'scripts/superdesk-items-common/views/grid-layout.html',
scope: {items: '='},
link: function(scope, elem, attrs) {
scope.view = 'mgrid';
scope.preview = function(item) {
scope.previewItem = item;
};
}
};
});
});
| app/scripts/superdesk-archive/directives.js | define([
'lodash',
'angular',
'require'
], function(_, angular, require) {
'use strict';
return angular.module('superdesk.archive.directives', [])
.directive('sdInlineMeta', function() {
return {
templateUrl: require.toUrl('./views/inline-meta.html'),
scope: {
'placeholder': '@',
'showmeta': '=',
'item': '=',
'setmeta': '&'
}
};
})
.directive('sdMediaPreview', ['api', function(api) {
return {
replace: true,
templateUrl: require.toUrl('./views/preview.html'),
scope: {item: '='},
link: function(scope, elem) {
scope.$watch('item', function(item) {
scope.contents = null;
if (item.type === 'composite') {
scope.contents = [];
var mainPackage = _.find(item.groups, {id: 'main'});
_.each(mainPackage.refs, function(r) {
api.ingest.getById(r.residRef)
.then(function(_item) {
var t = _item.type;
if (_.find(scope.contents, {type: t}) === undefined) {
scope.contents.push({type: t, items: [_item]});
} else {
scope.contents[_.findIndex(scope.contents, {type: t})].items.push(_item);
}
}, function(response) {
if (response.status === 404) {
console.log('Item not found');
}
});
});
}
});
}
};
}])
.directive('sdMediaView', ['keyboardManager', 'api', function(keyboardManager, api) {
return {
replace: true,
templateUrl: require.toUrl('./views/media-view.html'),
scope: {
items: '=',
item: '='
},
link: function(scope, elem) {
scope.singleItem = null;
scope.packageContents = null;
scope.prevEnabled = true;
scope.nextEnabled = true;
var getIndex = function(item) {
return _.findIndex(scope.items, item);
};
var setItem = function(item) {
scope.item = item;
scope.setSingleItem(item);
var index = getIndex(scope.item);
scope.prevEnabled = !!scope.items[index - 1];
scope.nextEnabled = !!scope.items[index + 1];
};
scope.prev = function() {
var index = getIndex(scope.item);
if (index > 0) {
setItem(scope.items[index - 1]);
}
};
scope.next = function() {
var index = getIndex(scope.item);
if (index !== -1 && index < scope.items.length - 1) {
setItem(scope.items[index + 1]);
}
};
keyboardManager.push('left', scope.prev);
keyboardManager.push('right', scope.next);
scope.$on('$destroy', function() {
keyboardManager.pop('left');
keyboardManager.pop('right');
});
scope.setSingleItem = function(item) {
scope.singleItem = item;
if (scope.singleItem !== null) {
if (scope.singleItem.type === 'composite') {
scope.packageContents = [];
var mainPackage = _.find(scope.singleItem.groups, {id: 'main'});
_.each(mainPackage.refs, function(r) {
api.ingest.getById(r.residRef)
.then(function(item) {
scope.packageContents.push(item);
}, function(response) {
if (response.status === 404) {
console.log('Item not found');
}
});
});
}
}
};
setItem(scope.item);
}
};
}])
.directive('sdSingleItem', [ function() {
return {
replace: true,
templateUrl: require.toUrl('./views/single-item-preview.html'),
scope: {
item: '=',
contents: '='
},
link: function(scope, elem) {
}
};
}])
.directive('sdSidebarLayout', ['$location', '$filter', function($location, $filter) {
return {
transclude: true,
templateUrl: require.toUrl('./views/sidebar.html')
};
}])
.directive('sdMediaBox', function() {
return {
restrict: 'A',
templateUrl: require.toUrl('./views/media-box.html'),
link: function(scope, element, attrs) {
if (!scope.activityFilter && scope.extras) {
scope.activityFilter = scope.extras.activityFilter;
}
scope.$watch('extras.view', function(view) {
switch (view) {
case 'mlist':
case 'compact':
scope.itemTemplate = require.toUrl('./views/media-box-list.html');
break;
default:
scope.itemTemplate = require.toUrl('./views/media-box-grid.html');
}
});
}
};
})
.directive('sdItemRendition', function() {
return {
templateUrl: require.toUrl('./views/item-rendition.html'),
scope: {item: '=', rendition: '@'},
link: function(scope, elem) {
scope.$watch('item.renditions[rendition].href', function(href) {
var figure = elem.find('figure'),
oldImg = figure.find('img').css('opacity', 0.5);
if (href) {
var img = new Image();
img.onload = function() {
if (oldImg.length) {
oldImg.replaceWith(img);
} else {
figure.prepend(img);
}
};
img.src = href;
}
});
}
};
})
.directive('sdSource', [ function() {
var typeMap = {
'video/mpeg': 'video/mp4'
};
return {
scope: {
sdSource: '='
},
link: function(scope, element) {
scope.$watch('sdSource', function(source) {
console.log('empty');
element.empty();
if (source) {
angular.element('<source />')
.attr('type', typeMap[source.mimetype] || source.mimetype)
.attr('src', source.href)
.appendTo(element);
}
});
}
};
}])
.directive('sdHtmlPreview', ['$sce', function($sce) {
return {
scope: {sdHtmlPreview: '='},
template: '<div ng-bind-html="html"></div>',
link: function(scope, elem, attrs) {
scope.$watch('sdHtmlPreview', function(html) {
scope.html = $sce.trustAsHtml(html);
});
}
};
}])
.directive('sdProviderMenu', ['$location', function($location) {
return {
scope: {items: '='},
templateUrl: require.toUrl('./views/provider-menu.html'),
link: function(scope, element, attrs) {
scope.setProvider = function(provider) {
scope.selected = provider;
$location.search('provider', scope.selected);
};
scope.$watchCollection(function() {
return $location.search();
}, function(search) {
if (search.provider) {
scope.selected = search.provider;
}
});
}
};
}])
.directive('sdToggleBox', function() {
return {
templateUrl: require.toUrl('./views/toggleBox.html'),
replace: true,
transclude: true,
scope: true,
link: function($scope, element, attrs) {
$scope.title = attrs.title;
$scope.isOpen = attrs.open === 'true';
$scope.icon = attrs.icon;
$scope.toggleModule = function() {
$scope.isOpen = !$scope.isOpen;
};
}
};
})
.directive('sdFilterUrgency', ['$location', function($location) {
return {
scope: true,
link: function($scope, element, attrs) {
$scope.urgency = {
min: $location.search().urgency_min || 1,
max: $location.search().urgency_max || 5
};
function handleUrgency(urgency) {
var min = Math.round(urgency.min);
var max = Math.round(urgency.max);
if (min !== 1 || max !== 5) {
var urgency_norm = {
min: min,
max: max
};
$location.search('urgency_min', urgency_norm.min);
$location.search('urgency_max', urgency_norm.max);
} else {
$location.search('urgency_min', null);
$location.search('urgency_max', null);
}
}
var handleUrgencyWrap = _.throttle(handleUrgency, 2000);
$scope.$watchCollection('urgency', function(newVal) {
handleUrgencyWrap(newVal);
});
}
};
}])
.directive('sdFilterContenttype', [ '$location', function($location) {
return {
restrict: 'A',
templateUrl: require.toUrl('./views/filter-contenttype.html'),
replace: true,
scope: {
items: '='
},
link: function(scope, element, attrs) {
scope.contenttype = [
{
term: 'text',
checked: false,
count: 0
},
{
term: 'audio',
checked: false,
count: 0
},
{
term: 'video',
checked: false,
count: 0
},
{
term: 'picture',
checked: false,
count: 0
},
{
term: 'graphic',
checked: false,
count: 0
},
{
term: 'composite',
checked: false,
count: 0
}
];
var search = $location.search();
if (search.type) {
var type = JSON.parse(search.type);
_.forEach(type, function(term) {
_.extend(_.first(_.where(scope.contenttype, {term: term})), {checked: true});
});
}
scope.$watchCollection('items', function() {
if (scope.items && scope.items._facets !== undefined) {
_.forEach(scope.items._facets.type.terms, function(type) {
_.extend(_.first(_.where(scope.contenttype, {term: type.term})), type);
});
}
});
scope.setContenttypeFilter = function() {
var contenttype = _.map(_.where(scope.contenttype, {'checked': true}), function(t) {
return t.term;
});
if (contenttype.length === 0) {
$location.search('type', null);
} else {
$location.search('type', JSON.stringify(contenttype));
}
};
}
};
}])
.directive('sdGridLayout', function() {
return {
templateUrl: 'scripts/superdesk-items-common/views/grid-layout.html',
scope: {items: '='},
link: function(scope, elem, attrs) {
scope.view = 'mgrid';
scope.preview = function(item) {
scope.previewItem = item;
};
}
};
});
});
| fix(archive): remove obsolete source directive
| app/scripts/superdesk-archive/directives.js | fix(archive): remove obsolete source directive | <ide><path>pp/scripts/superdesk-archive/directives.js
<ide> }
<ide> };
<ide> })
<del> .directive('sdSource', [ function() {
<del> var typeMap = {
<del> 'video/mpeg': 'video/mp4'
<del> };
<del> return {
<del> scope: {
<del> sdSource: '='
<del> },
<del> link: function(scope, element) {
<del> scope.$watch('sdSource', function(source) {
<del> console.log('empty');
<del> element.empty();
<del> if (source) {
<del> angular.element('<source />')
<del> .attr('type', typeMap[source.mimetype] || source.mimetype)
<del> .attr('src', source.href)
<del> .appendTo(element);
<del> }
<del> });
<del> }
<del> };
<del> }])
<ide> .directive('sdHtmlPreview', ['$sce', function($sce) {
<ide> return {
<ide> scope: {sdHtmlPreview: '='}, |
|
Java | apache-2.0 | 2d079ac843ebcb335f2ef7d6952f9700a16fddde | 0 | java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity | package com.java110.acct.api;
import com.java110.acct.bmo.account.IGetAccountBMO;
import com.java110.dto.account.AccountDto;
import com.java110.dto.accountDetail.AccountDetailDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName AccountApi
* @Description TODO
* @Author wuxw
* @Date 2021/5/4 12:44
* @Version 1.0
* add by wuxw 2021/5/4
**/
@RestController
@RequestMapping(value = "/account")
public class AccountApi {
@Autowired
private IGetAccountBMO getAccountBMOImpl;
/**
* 微信删除消息模板
*
* @param storeId 小区ID
* @return
* @serviceCode /account/queryAccount
* @path /app/account/queryAccount
*/
@RequestMapping(value = "/queryAccount", method = RequestMethod.GET)
public ResponseEntity<String> queryAccount(@RequestHeader(value = "store-id", required = false) String storeId,
@RequestParam(value = "page") int page,
@RequestParam(value = "row") int row) {
AccountDto accountDto = new AccountDto();
accountDto.setPage(page);
accountDto.setRow(row);
accountDto.setObjId(storeId);
return getAccountBMOImpl.get(accountDto);
}
/**
* 查询账户明细
*
* @param storeId 小区ID
* @return
* @serviceCode /account/queryAccountDetail
* @path /app/account/queryAccountDetail
*/
@RequestMapping(value = "/queryAccountDetail", method = RequestMethod.GET)
public ResponseEntity<String> queryAccountDetail(@RequestHeader(value = "store-id", required = false) String storeId,
@RequestParam(value = "acctId", required = false) String acctId,
@RequestParam(value = "page") int page,
@RequestParam(value = "row") int row) {
AccountDetailDto accountDto = new AccountDetailDto();
accountDto.setPage(page);
accountDto.setRow(row);
accountDto.setObjId(storeId);
accountDto.setAcctId(acctId);
return getAccountBMOImpl.getDetail(accountDto);
}
}
| service-acct/src/main/java/com/java110/acct/api/AccountApi.java | package com.java110.acct.api;
import com.java110.acct.bmo.account.IGetAccountBMO;
import com.java110.dto.account.AccountDto;
import com.java110.dto.accountDetail.AccountDetailDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName AccountApi
* @Description TODO
* @Author wuxw
* @Date 2021/5/4 12:44
* @Version 1.0
* add by wuxw 2021/5/4
**/
@RestController
@RequestMapping(value = "/account")
public class AccountApi {
@Autowired
private IGetAccountBMO getAccountBMOImpl;
/**
* 微信删除消息模板
*
* @param storeId 小区ID
* @return
* @serviceCode /account/queryAccount
* @path /app/account/queryAccount
*/
@RequestMapping(value = "/queryAccount", method = RequestMethod.GET)
public ResponseEntity<String> queryAccount(@RequestHeader(value = "store-id", required = false) String storeId,
@RequestParam(value = "page") int page,
@RequestParam(value = "row") int row) {
AccountDto accountDto = new AccountDto();
accountDto.setPage(page);
accountDto.setRow(row);
accountDto.setObjId(storeId);
return getAccountBMOImpl.get(accountDto);
}
/**
* 查询账户明细
*
* @param storeId 小区ID
* @return
* @serviceCode /account/queryAccount
* @path /app/account/queryAccount
*/
@RequestMapping(value = "/queryAccountDetail", method = RequestMethod.GET)
public ResponseEntity<String> queryAccountDetail(@RequestHeader(value = "store-id", required = false) String storeId,
@RequestParam(value = "acctId", required = false) String acctId,
@RequestParam(value = "page") int page,
@RequestParam(value = "row") int row) {
AccountDetailDto accountDto = new AccountDetailDto();
accountDto.setPage(page);
accountDto.setRow(row);
accountDto.setObjId(storeId);
accountDto.setAcctId(acctId);
return getAccountBMOImpl.getDetail(accountDto);
}
}
| 游湖阿底阿妈
| service-acct/src/main/java/com/java110/acct/api/AccountApi.java | 游湖阿底阿妈 | <ide><path>ervice-acct/src/main/java/com/java110/acct/api/AccountApi.java
<ide> *
<ide> * @param storeId 小区ID
<ide> * @return
<del> * @serviceCode /account/queryAccount
<del> * @path /app/account/queryAccount
<add> * @serviceCode /account/queryAccountDetail
<add> * @path /app/account/queryAccountDetail
<ide> */
<ide> @RequestMapping(value = "/queryAccountDetail", method = RequestMethod.GET)
<ide> public ResponseEntity<String> queryAccountDetail(@RequestHeader(value = "store-id", required = false) String storeId, |
|
Java | mit | 4a50b6e43d6278c75763aa57d6797cd097177b47 | 0 | cancobanoglu/java-game-server,chongtianfeiyu/java-game-server,wuzhenda/java-game-server,rayue/java-game-server,wuzhenda/java-game-server,rayue/java-game-server,niuqinghua/java-game-server,feamorx86/java-game-server,menacher/java-game-server,feamorx86/java-game-server,chongtianfeiyu/java-game-server,niuqinghua/java-game-server,xiexingguang/java-game-server,cancobanoglu/java-game-server,feamorx86/java-game-server,menacher/java-game-server,wuzhenda/java-game-server,niuqinghua/java-game-server,xiexingguang/java-game-server,cancobanoglu/java-game-server,menacher/java-game-server,rayue/java-game-server,xiexingguang/java-game-server | package org.menacheri.jetserver.concurrent;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.menacheri.jetserver.app.GameRoom;
public interface LaneStrategy<LANE_ID_TYPE, UNDERLYING_LANE, GROUP>
{
Lane<LANE_ID_TYPE, UNDERLYING_LANE> chooseLane(GROUP group);
public enum LaneStrategies implements
LaneStrategy<String, ExecutorService, GameRoom>
{
ROUND_ROBIN
{
final AtomicInteger currentLane = new AtomicInteger(0);
final int laneSize = lanes.size();
@Override
public Lane<String, ExecutorService> chooseLane(GameRoom group)
{
synchronized (currentLane)
{
if (currentLane.get() == laneSize)
{
currentLane.set(0);
}
}
return lanes.get(currentLane.getAndIncrement());
}
},
/**
* This Strategy groups sessions by GameRoom on a lane. Each time a
* session is added, it will check for the session's game room and
* return back the lane on which the GameRoom is operating. This way all
* sessions will be running on the same thread and inter-session
* messaging will be fast synchronous message calls. The disadvantage is
* that if there are some GameRooms with huge number of sessions and
* some with few, possibility of uneven load on multiple CPU cores is
* possible.
*
* @author Abraham Menacherry
*
*/
GROUP_BY_ROOM
{
private final ConcurrentMap<GameRoom, Lane<String, ExecutorService>> roomLaneMap = new ConcurrentHashMap<GameRoom, Lane<String, ExecutorService>>();
private final ConcurrentMap<Lane<String, ExecutorService>, AtomicInteger> laneSessionCounter = new ConcurrentHashMap<Lane<String, ExecutorService>, AtomicInteger>();
@Override
public Lane<String, ExecutorService> chooseLane(GameRoom room)
{
Lane<String, ExecutorService> lane = roomLaneMap.get(room);
if (null == lane)
{
synchronized (laneSessionCounter)
{
if (laneSessionCounter.isEmpty())
{
for (Lane<String, ExecutorService> theLane : lanes)
{
laneSessionCounter.put(theLane,
new AtomicInteger(0));
}
}
Set<Lane<String, ExecutorService>> laneSet = laneSessionCounter
.keySet();
int min = 0;
for (Lane<String, ExecutorService> theLane : laneSet)
{
AtomicInteger counter = laneSessionCounter
.get(theLane);
int numOfSessions = counter.get();
// if numOfSessions is 0, then this lane/thread/core
// is not tagged to a gameroom and it can be used.
if (numOfSessions == 0)
{
lane = theLane;
break;
}
else
{
// reset min for first time.
if (min == 0)
{
min = numOfSessions;
lane = theLane;
}
// If numOfSessions is less than min then
// replace min with that value, also set the
// lane.
if (numOfSessions < min)
{
min = numOfSessions;
lane = theLane;
}
}
}
roomLaneMap.put(room, lane);
}
}
// A new session has chosen the lane, hence the session counter
// needs to be incremented.
laneSessionCounter.get(lane).incrementAndGet();
// TODO how to reduce count on session close?
return lane;
}
};
final List<Lane<String, ExecutorService>> lanes = Lanes.LANES
.getJetLanes();
}
}
| jetserver/src/main/java/org/menacheri/jetserver/concurrent/LaneStrategy.java | package org.menacheri.jetserver.concurrent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.menacheri.jetserver.app.GameRoom;
public interface LaneStrategy
{
<I, T, O> Lane<I, T> chooseLane(O group);
public enum LaneStrategies implements LaneStrategy
{
ROUND_ROBIN
{
final AtomicInteger currentLane = new AtomicInteger(0);
@SuppressWarnings("unchecked")
@Override
public Lane<String, ExecutorService> chooseLane(Object group)
{
synchronized (currentLane)
{
if (currentLane.get() == lanes.size())
{
currentLane.set(0);
}
}
return lanes.get(currentLane.getAndIncrement());
}
},
GAME_ROOM
{
@SuppressWarnings("rawtypes")
Map laneRoomMap = new HashMap();
@SuppressWarnings({ "hiding", "unchecked" })
@Override
public <String, ExecutorService, GameRoom> Lane<String, ExecutorService> chooseLane(
GameRoom group)
{
synchronized (laneRoomMap)
{
if (laneRoomMap.isEmpty())
{
for (@SuppressWarnings("rawtypes")
Lane lane : lanes)
{
List<GameRoom> roomList = new ArrayList<GameRoom>();
laneRoomMap.put(lane, roomList);
}
}
}
return null;
}
};
final List<Lane<String, ExecutorService>> lanes = Lanes.LANES
.getJetLanes();
}
}
| GROUP_BY_ROOM lane strategy has been implemented. | jetserver/src/main/java/org/menacheri/jetserver/concurrent/LaneStrategy.java | GROUP_BY_ROOM lane strategy has been implemented. | <ide><path>etserver/src/main/java/org/menacheri/jetserver/concurrent/LaneStrategy.java
<ide> package org.menacheri.jetserver.concurrent;
<ide>
<del>import java.util.ArrayList;
<del>import java.util.HashMap;
<ide> import java.util.List;
<del>import java.util.Map;
<add>import java.util.Set;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.ConcurrentMap;
<ide> import java.util.concurrent.ExecutorService;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.menacheri.jetserver.app.GameRoom;
<ide>
<del>public interface LaneStrategy
<add>public interface LaneStrategy<LANE_ID_TYPE, UNDERLYING_LANE, GROUP>
<ide> {
<del> <I, T, O> Lane<I, T> chooseLane(O group);
<add> Lane<LANE_ID_TYPE, UNDERLYING_LANE> chooseLane(GROUP group);
<ide>
<del> public enum LaneStrategies implements LaneStrategy
<add> public enum LaneStrategies implements
<add> LaneStrategy<String, ExecutorService, GameRoom>
<ide> {
<ide>
<ide> ROUND_ROBIN
<ide> {
<ide> final AtomicInteger currentLane = new AtomicInteger(0);
<del>
<del> @SuppressWarnings("unchecked")
<add> final int laneSize = lanes.size();
<add>
<ide> @Override
<del> public Lane<String, ExecutorService> chooseLane(Object group)
<add> public Lane<String, ExecutorService> chooseLane(GameRoom group)
<ide> {
<ide> synchronized (currentLane)
<ide> {
<del> if (currentLane.get() == lanes.size())
<add> if (currentLane.get() == laneSize)
<ide> {
<ide> currentLane.set(0);
<ide> }
<ide> return lanes.get(currentLane.getAndIncrement());
<ide> }
<ide> },
<del> GAME_ROOM
<add> /**
<add> * This Strategy groups sessions by GameRoom on a lane. Each time a
<add> * session is added, it will check for the session's game room and
<add> * return back the lane on which the GameRoom is operating. This way all
<add> * sessions will be running on the same thread and inter-session
<add> * messaging will be fast synchronous message calls. The disadvantage is
<add> * that if there are some GameRooms with huge number of sessions and
<add> * some with few, possibility of uneven load on multiple CPU cores is
<add> * possible.
<add> *
<add> * @author Abraham Menacherry
<add> *
<add> */
<add> GROUP_BY_ROOM
<ide> {
<del> @SuppressWarnings("rawtypes")
<del> Map laneRoomMap = new HashMap();
<add> private final ConcurrentMap<GameRoom, Lane<String, ExecutorService>> roomLaneMap = new ConcurrentHashMap<GameRoom, Lane<String, ExecutorService>>();
<add> private final ConcurrentMap<Lane<String, ExecutorService>, AtomicInteger> laneSessionCounter = new ConcurrentHashMap<Lane<String, ExecutorService>, AtomicInteger>();
<ide>
<del> @SuppressWarnings({ "hiding", "unchecked" })
<ide> @Override
<del> public <String, ExecutorService, GameRoom> Lane<String, ExecutorService> chooseLane(
<del> GameRoom group)
<add> public Lane<String, ExecutorService> chooseLane(GameRoom room)
<ide> {
<del> synchronized (laneRoomMap)
<add> Lane<String, ExecutorService> lane = roomLaneMap.get(room);
<add> if (null == lane)
<ide> {
<del> if (laneRoomMap.isEmpty())
<add> synchronized (laneSessionCounter)
<ide> {
<del> for (@SuppressWarnings("rawtypes")
<del> Lane lane : lanes)
<add> if (laneSessionCounter.isEmpty())
<ide> {
<del> List<GameRoom> roomList = new ArrayList<GameRoom>();
<del> laneRoomMap.put(lane, roomList);
<add> for (Lane<String, ExecutorService> theLane : lanes)
<add> {
<add> laneSessionCounter.put(theLane,
<add> new AtomicInteger(0));
<add> }
<ide> }
<add> Set<Lane<String, ExecutorService>> laneSet = laneSessionCounter
<add> .keySet();
<add> int min = 0;
<add> for (Lane<String, ExecutorService> theLane : laneSet)
<add> {
<add> AtomicInteger counter = laneSessionCounter
<add> .get(theLane);
<add> int numOfSessions = counter.get();
<add> // if numOfSessions is 0, then this lane/thread/core
<add> // is not tagged to a gameroom and it can be used.
<add> if (numOfSessions == 0)
<add> {
<add> lane = theLane;
<add> break;
<add> }
<add> else
<add> {
<add> // reset min for first time.
<add> if (min == 0)
<add> {
<add> min = numOfSessions;
<add> lane = theLane;
<add> }
<add> // If numOfSessions is less than min then
<add> // replace min with that value, also set the
<add> // lane.
<add> if (numOfSessions < min)
<add> {
<add> min = numOfSessions;
<add> lane = theLane;
<add> }
<add> }
<add> }
<add>
<add> roomLaneMap.put(room, lane);
<ide> }
<ide> }
<del>
<del> return null;
<add> // A new session has chosen the lane, hence the session counter
<add> // needs to be incremented.
<add> laneSessionCounter.get(lane).incrementAndGet();
<add> // TODO how to reduce count on session close?
<add> return lane;
<ide> }
<del>
<add>
<ide> };
<ide>
<ide> final List<Lane<String, ExecutorService>> lanes = Lanes.LANES
<ide> .getJetLanes();
<ide> }
<del>
<add>
<add>
<ide> } |
|
Java | apache-2.0 | 261cbf94e8f54e1664f6a2717e44fa9189bc5dcb | 0 | Ali-Razmjoo/zaproxy,UjuE/zaproxy,robocoder/zaproxy,meitar/zaproxy,kingthorin/zaproxy,thamizarasu/zaproxy,DJMIN/zaproxy,robocoder/zaproxy,cassiodeveloper/zaproxy,jorik041/zaproxy,JordanGS/zaproxy,tjackiw/zaproxy,thc202/zaproxy,zapbot/zaproxy,zaproxy/zaproxy,efdutra/zaproxy,zapbot/zaproxy,NVolcz/zaproxy,gsavastano/zaproxy,ozzyjohnson/zaproxy,lightsey/zaproxy,zapbot/zaproxy,pdehaan/zaproxy,zaproxy/zaproxy,meitar/zaproxy,tjackiw/zaproxy,UjuE/zaproxy,cassiodeveloper/zaproxy,mustafa421/zaproxy,psiinon/zaproxy,tjackiw/zaproxy,Harinus/zaproxy,urgupluoglu/zaproxy,kingthorin/zaproxy,jorik041/zaproxy,thc202/zaproxy,mabdi/zaproxy,MD14/zaproxy,ozzyjohnson/zaproxy,psiinon/zaproxy,0xkasun/zaproxy,veggiespam/zaproxy,urgupluoglu/zaproxy,mario-areias/zaproxy,ozzyjohnson/zaproxy,gsavastano/zaproxy,urgupluoglu/zaproxy,pdehaan/zaproxy,surikato/zaproxy,gmaran23/zaproxy,UjuE/zaproxy,NVolcz/zaproxy,efdutra/zaproxy,zaproxy/zaproxy,ozzyjohnson/zaproxy,lightsey/zaproxy,jorik041/zaproxy,rajiv65/zaproxy,DJMIN/zaproxy,gsavastano/zaproxy,kingthorin/zaproxy,efdutra/zaproxy,ozzyjohnson/zaproxy,lightsey/zaproxy,zapbot/zaproxy,UjuE/zaproxy,tjackiw/zaproxy,veggiespam/zaproxy,robocoder/zaproxy,urgupluoglu/zaproxy,veggiespam/zaproxy,zaproxy/zaproxy,thamizarasu/zaproxy,ozzyjohnson/zaproxy,meitar/zaproxy,urgupluoglu/zaproxy,gmaran23/zaproxy,NVolcz/zaproxy,urgupluoglu/zaproxy,psiinon/zaproxy,mustafa421/zaproxy,meitar/zaproxy,pdehaan/zaproxy,psiinon/zaproxy,surikato/zaproxy,thc202/zaproxy,MD14/zaproxy,Harinus/zaproxy,profjrr/zaproxy,NVolcz/zaproxy,DJMIN/zaproxy,mario-areias/zaproxy,Harinus/zaproxy,Ye-Yong-Chi/zaproxy,efdutra/zaproxy,gsavastano/zaproxy,rajiv65/zaproxy,gsavastano/zaproxy,MD14/zaproxy,lightsey/zaproxy,mario-areias/zaproxy,mabdi/zaproxy,JordanGS/zaproxy,profjrr/zaproxy,zaproxy/zaproxy,thc202/zaproxy,kingthorin/zaproxy,Ali-Razmjoo/zaproxy,mario-areias/zaproxy,JordanGS/zaproxy,profjrr/zaproxy,Ye-Yong-Chi/zaproxy,meitar/zaproxy,kingthorin/zaproxy,gsavastano/zaproxy,profjrr/zaproxy,zapbot/zaproxy,ozzyjohnson/zaproxy,JordanGS/zaproxy,robocoder/zaproxy,zapbot/zaproxy,DJMIN/zaproxy,thc202/zaproxy,thamizarasu/zaproxy,thamizarasu/zaproxy,surikato/zaproxy,tjackiw/zaproxy,zapbot/zaproxy,0xkasun/zaproxy,Ali-Razmjoo/zaproxy,lightsey/zaproxy,kingthorin/zaproxy,psiinon/zaproxy,meitar/zaproxy,0xkasun/zaproxy,kingthorin/zaproxy,rajiv65/zaproxy,urgupluoglu/zaproxy,rajiv65/zaproxy,efdutra/zaproxy,thamizarasu/zaproxy,profjrr/zaproxy,Ye-Yong-Chi/zaproxy,NVolcz/zaproxy,Harinus/zaproxy,jorik041/zaproxy,mustafa421/zaproxy,NVolcz/zaproxy,tjackiw/zaproxy,Harinus/zaproxy,thamizarasu/zaproxy,rajiv65/zaproxy,jorik041/zaproxy,mabdi/zaproxy,mustafa421/zaproxy,MD14/zaproxy,surikato/zaproxy,Ali-Razmjoo/zaproxy,Ye-Yong-Chi/zaproxy,robocoder/zaproxy,meitar/zaproxy,veggiespam/zaproxy,thc202/zaproxy,mabdi/zaproxy,veggiespam/zaproxy,Ye-Yong-Chi/zaproxy,JordanGS/zaproxy,cassiodeveloper/zaproxy,pdehaan/zaproxy,psiinon/zaproxy,robocoder/zaproxy,Ali-Razmjoo/zaproxy,mario-areias/zaproxy,zaproxy/zaproxy,mario-areias/zaproxy,pdehaan/zaproxy,Harinus/zaproxy,0xkasun/zaproxy,Ye-Yong-Chi/zaproxy,psiinon/zaproxy,jorik041/zaproxy,DJMIN/zaproxy,cassiodeveloper/zaproxy,profjrr/zaproxy,tjackiw/zaproxy,DJMIN/zaproxy,gmaran23/zaproxy,efdutra/zaproxy,profjrr/zaproxy,veggiespam/zaproxy,Ali-Razmjoo/zaproxy,jorik041/zaproxy,meitar/zaproxy,pdehaan/zaproxy,rajiv65/zaproxy,cassiodeveloper/zaproxy,mabdi/zaproxy,UjuE/zaproxy,gsavastano/zaproxy,mario-areias/zaproxy,Ye-Yong-Chi/zaproxy,mustafa421/zaproxy,veggiespam/zaproxy,robocoder/zaproxy,0xkasun/zaproxy,mustafa421/zaproxy,surikato/zaproxy,0xkasun/zaproxy,Harinus/zaproxy,UjuE/zaproxy,gmaran23/zaproxy,pdehaan/zaproxy,UjuE/zaproxy,cassiodeveloper/zaproxy,lightsey/zaproxy,MD14/zaproxy,gmaran23/zaproxy,mabdi/zaproxy,cassiodeveloper/zaproxy,mustafa421/zaproxy,rajiv65/zaproxy,NVolcz/zaproxy,efdutra/zaproxy,DJMIN/zaproxy,MD14/zaproxy,thc202/zaproxy,Ali-Razmjoo/zaproxy,mabdi/zaproxy,JordanGS/zaproxy,MD14/zaproxy,thamizarasu/zaproxy,JordanGS/zaproxy,0xkasun/zaproxy,surikato/zaproxy,gmaran23/zaproxy,gmaran23/zaproxy,surikato/zaproxy,zaproxy/zaproxy,lightsey/zaproxy | /*
* Created on Jun 14, 2004
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012:02/01 Changed getHostPort() to return proper port number even if it
// is not explicitly specified in URI
// ZAP: 2011/08/04 Changed to support Logging
// ZAP: 2011/10/29 Log errors
// ZAP: 2011/11/03 Changed isImage() to prevent a NullPointerException when the path doesn't exist
// ZAP: 2011/12/09 Changed HttpRequestHeader(String method, URI uri, String version) to add
// the Cache-Control header field when the HTTP version is 1.1 and changed a if condition to
// validate the variable version instead of the variable method.
// ZAP: 2012/03/15 Changed to use the class StringBuilder instead of StringBuffer. Reworked some methods.
// ZAP: 2012/04/23 Added @Override annotation to all appropriate methods.
// ZAP: 2012/06/24 Added method to add Cookies of type java.net.HttpCookie to request header
// ZAP: 2012/06/24 Added new method of getting cookies from the request header.
// ZAP: 2012/10/08 Issue 361: getHostPort on HttpRequestHeader for HTTPS CONNECT
// requests returns the wrong port
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/03/08 Improved parse error reporting
// ZAP: 2013/04/14 Issue 596: Rename the method HttpRequestHeader.getSecure to isSecure
package org.parosproxy.paros.network;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.log4j.Logger;
public class HttpRequestHeader extends HttpHeader {
private static final long serialVersionUID = 4156598327921777493L;
private static final Logger log = Logger.getLogger(HttpRequestHeader.class);
// method list
public final static String OPTIONS = "OPTIONS";
public final static String GET = "GET";
public final static String HEAD = "HEAD";
public final static String POST = "POST";
public final static String PUT = "PUT";
public final static String DELETE = "DELETE";
public final static String TRACE = "TRACE";
public final static String CONNECT = "CONNECT";
// ZAP: Added method array
public final static String[] METHODS = {OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT};
public final static String HOST = "Host";
private static final Pattern patternRequestLine = Pattern.compile(p_METHOD + p_SP + p_URI + p_SP + p_VERSION, Pattern.CASE_INSENSITIVE);
// private static final Pattern patternHostHeader
// = Pattern.compile("([^:]+)\\s*?:?\\s*?(\\d*?)");
private static final Pattern patternImage = Pattern.compile("\\.(bmp|ico|jpg|jpeg|gif|tiff|tif|png)\\z", Pattern.CASE_INSENSITIVE);
private static final Pattern patternPartialRequestLine = Pattern.compile("\\A *(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT)\\b", Pattern.CASE_INSENSITIVE);
private String mMethod = "";
private URI mUri = null;
private String mHostName = "";
/**
* The host port number of this request message, a non-negative integer.
* <p>
* <strong>Note:</strong> All the modifications to the instance variable
* {@code mHostPort} must be done through the method
* {@code setHostPort(int)}, so a valid and correct value is set when no
* port number is defined (which is represented with the negative integer
* -1).
* </p>
*
* @see #getHostPort()
* @see #setHostPort(int)
* @see URI#getPort()
*/
private int mHostPort;
private boolean mIsSecure = false;
/**
* Constructor for an empty header.
*
*/
public HttpRequestHeader() {
clear();
}
/**
* Constructor of a request header with the string.
*
* @param data
* @param isSecure If this request header is secure. URL will be converted
* to HTTPS if secure = true.
* @throws HttpMalformedHeaderException
*/
public HttpRequestHeader(String data, boolean isSecure) throws HttpMalformedHeaderException {
this();
setMessage(data, isSecure);
}
/**
* Constructor of a request header with the string. Whether this is a secure
* header depends on the URL given.
*
* @param data
* @throws HttpMalformedHeaderException
*/
public HttpRequestHeader(String data) throws HttpMalformedHeaderException {
this();
setMessage(data);
}
@Override
public void clear() {
super.clear();
mMethod = "";
mUri = null;
mHostName = "";
setHostPort(-1);
mMsgHeader = "";
}
public HttpRequestHeader(String method, URI uri, String version) throws HttpMalformedHeaderException {
this(method + " " + uri.toString() + " " + version.toUpperCase() + CRLF + CRLF);
try {
setHeader(HOST, uri.getHost() + (uri.getPort() > 0 ? ":" + Integer.toString(uri.getPort()) : ""));
} catch (URIException e) {
log.error(e.getMessage(), e);
}
setHeader(USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;)");
setHeader(PRAGMA, "no-cache");
// ZAP: added the Cache-Control header field to comply with HTTP/1.1
if (version.equalsIgnoreCase(HTTP11)) {
setHeader(CACHE_CONTROL, "no-cache");
}
setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded");
setHeader(ACCEPT_ENCODING, null);
// ZAP: changed from method to version
if (version.equalsIgnoreCase(HTTP11)) {
setContentLength(0);
}
}
/**
* Set this request header with the given message.
*
* @param data
* @param isSecure If this request header is secure. URL will be converted
* to HTTPS if secure = true.
* @throws HttpMalformedHeaderException
*/
public void setMessage(String data, boolean isSecure) throws HttpMalformedHeaderException {
super.setMessage(data);
try {
parse(isSecure);
} catch (HttpMalformedHeaderException e) {
mMalformedHeader = true;
if (log.isDebugEnabled()) {
log.debug("Malformed header: " + data, e);
}
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
mMalformedHeader = true;
throw new HttpMalformedHeaderException(e.getMessage());
}
}
/**
* Set this request header with the given message. Whether this is a secure
* header depends on the URL given.
*/
@Override
public void setMessage(String data) throws HttpMalformedHeaderException {
this.setMessage(data, false);
}
/**
* Get the HTTP method (GET, POST ... etc).
*
* @return
*/
public String getMethod() {
return mMethod;
}
/**
* Set the HTTP method of this request header.
*
* @param method
*/
public void setMethod(String method) {
mMethod = method.toUpperCase();
}
/**
* Get the URI of this request header.
*
* @return
*/
public URI getURI() {
return mUri;
}
/**
* Set the URI of this request header.
*
* @param uri
* @throws URIException
* @throws NullPointerException
*/
public void setURI(URI uri) throws URIException, NullPointerException {
if (uri.getScheme() == null || uri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + "/" + mUri.toString(), true);
} else {
mUri = uri;
}
if (uri.getScheme().equalsIgnoreCase(HTTPS)) {
mIsSecure = true;
} else {
mIsSecure = false;
}
setHostPort(mUri.getPort());
}
/**
* Get if this request header is under secure connection.
*
* @return
* @deprecated Replaced by {@link #isSecure()}. It will be removed in a future release.
*/
@Deprecated
public boolean getSecure() {
return mIsSecure;
}
/**
* Tells whether the request is secure, or not. A request is considered secure if it's using the HTTPS protocol.
*
* @return {@code true} if the request is secure, {@code false} otherwise.
*/
public boolean isSecure() {
return mIsSecure;
}
/**
* Set if this request header is under secure connection.
*
* @param isSecure
* @throws URIException
* @throws NullPointerException
*/
public void setSecure(boolean isSecure) throws URIException, NullPointerException {
mIsSecure = isSecure;
if (mUri == null) {
// mUri not yet set
return;
}
URI newUri = mUri;
// check if URI consistent
if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
newUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
} else if (!isSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) {
newUri = new URI(mUri.toString().replaceFirst(HTTPS, HTTP), true);
}
if (newUri != mUri) {
mUri = newUri;
setHostPort(mUri.getPort());
}
}
/**
* Set the HTTP version of this request header.
*/
@Override
public void setVersion(String version) {
mVersion = version.toUpperCase();
}
/**
* Get the content length in this request header. If the content length is
* undetermined, 0 will be returned.
*/
@Override
public int getContentLength() {
if (mContentLength == -1) {
return 0;
}
return mContentLength;
}
/**
* Parse this request header.
*
* @param isSecure
* @return
* @throws URIException
* @throws NullPointerException
*/
private void parse(boolean isSecure) throws URIException, HttpMalformedHeaderException {
mIsSecure = isSecure;
Matcher matcher = patternRequestLine.matcher(mStartLine);
if (!matcher.find()) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException("Failed to find pattern: " + patternRequestLine);
}
mMethod = matcher.group(1);
String sUri = matcher.group(2);
mVersion = matcher.group(3);
if (!mVersion.equalsIgnoreCase(HTTP09) && !mVersion.equalsIgnoreCase(HTTP10) && !mVersion.equalsIgnoreCase(HTTP11)) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException("Unexpected version: " + mVersion);
}
mUri = parseURI(sUri);
if (mUri.getScheme() == null || mUri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true);
}
if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
}
if (mUri.getScheme().equalsIgnoreCase(HTTPS)) {
setSecure(true);
}
String hostHeader = null;
if (mMethod.equalsIgnoreCase(CONNECT)) {
hostHeader = sUri;
parseHostName(hostHeader);
} else {
mHostName = mUri.getHost();
setHostPort(mUri.getPort());
}
}
private void parseHostName(String hostHeader) {
// no host header given but a valid host name already exist.
if (hostHeader == null) {
return;
}
int port = -1;
int pos = 0;
if ((pos = hostHeader.indexOf(':', 2)) > -1) {
mHostName = hostHeader.substring(0, pos).trim();
try {
port = Integer.parseInt(hostHeader.substring(pos + 1));
} catch (NumberFormatException e) {
}
} else {
mHostName = hostHeader.trim();
}
setHostPort(port);
}
/**
* Get the host name in this request header.
*
* @return Host name.
*/
public String getHostName() {
String hostName = mHostName;
try {
// ZAP: fixed cases, where host name is null
hostName = ((mUri.getHost() != null) ? mUri.getHost() : mHostName);
} catch (URIException e) {
if (log.isDebugEnabled()) {
log.warn(e);
}
}
return hostName;
}
/**
* Gets the host port number of this request message, a non-negative
* integer.
* <p>
* If no port is defined the default port for the used scheme will be
* returned, either 80 for HTTP or 443 for HTTPS.
* </p>
*
* @return the host port number, a non-negative integer
*/
public int getHostPort() {
return mHostPort;
}
/**
* Sets the host port number of this request message.
* <p>
* If the given {@code port} number is negative (usually -1 to represent
* that no port number is defined), the port number set will be the default
* port number for the used scheme known using the method
* {@code isSecure()}, either 80 for HTTP or 443 for HTTPS.
* </p>
*
* @param port
* the new port number
* @see #mHostPort
* @see #isSecure()
* @see URI#getPort()
*/
private void setHostPort(int port) {
if (port > -1) {
mHostPort = port;
} else if (this.isSecure()) {
mHostPort = 443;
} else {
mHostPort = 80;
}
}
/**
* Return if this request header is a image request basing on the path
* suffix.
*/
@Override
public boolean isImage() {
try {
// ZAP: prevents a NullPointerException when no path exists
final String path = getURI().getPath();
if (path != null) {
return (patternImage.matcher(path).find());
}
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return false;
}
/**
* Return if the data given is a request header basing on the first start
* line.
*
* @param data
* @return
*/
public static boolean isRequestLine(String data) {
return patternPartialRequestLine.matcher(data).find();
}
/**
* Return the prime header (first line).
*/
@Override
public String getPrimeHeader() {
return getMethod() + " " + getURI().toString() + " " + getVersion();
}
/*
* private static final char[] DELIM_UNWISE_CHAR = { '<', '>', '#', '"', '
* ', '{', '}', '|', '\\', '^', '[', ']', '`' };
*/
private static final String DELIM = "<>#\"";
private static final String UNWISE = "{}|\\^[]`";
private static final String DELIM_UNWISE = DELIM + UNWISE;
public static URI parseURI(String sUri) throws URIException {
URI uri = null;
int len = sUri.length();
StringBuilder sb = new StringBuilder(len);
char[] charray = new char[1];
String s = null;
for (int i = 0; i < len; i++) {
char ch = sUri.charAt(i);
//String ch = sUri.substring(i, i+1);
if (DELIM_UNWISE.indexOf(ch) >= 0) {
// check if unwise or delim in RFC. If so, encode it.
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
} else if (ch == '%') {
// % is exception - no encoding to be done because some server may not handle
// correctly when % is invalid.
//
//sb.append(ch);
// if % followed by hex, no encode.
try {
String hex = sUri.substring(i + 1, i + 3);
Integer.parseInt(hex, 16);
sb.append(ch);
} catch (Exception e) {
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
}
} else if (ch == ' ') {
// if URLencode, '+' will be appended.
sb.append("%20");
} else {
sb.append(ch);
}
}
uri = new URI(sb.toString(), true);
return uri;
}
// Construct new GET url of request
// Based on getParams
public void setGetParams(TreeSet<HtmlParameter> getParams) {
if (mUri == null) {
return;
}
if (getParams.isEmpty()) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
StringBuilder sbQuery = new StringBuilder();
for (HtmlParameter parameter : getParams) {
if (parameter.getType() != HtmlParameter.Type.url) {
continue;
}
sbQuery.append(parameter.getName());
sbQuery.append('=');
sbQuery.append(parameter.getValue());
sbQuery.append('&');
}
if (sbQuery.length() <= 2) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
String query = sbQuery.substring(0, sbQuery.length() - 1);
try {
//The previous behaviour was escaping the query,
//so it is maintained with the use of setQuery.
mUri.setQuery(query);
} catch (URIException e) {
log.error(e.getMessage(), e);
}
}
/**
* Construct new "Cookie:" line in request header based on HttpCookies.
*
* @param cookies the new cookies
*/
public void setCookies(List<HttpCookie> cookies) {
if (cookies.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for(HttpCookie c:cookies){
sbData.append(c.getName());
sbData.append('=');
sbData.append(c.getValue());
sbData.append("; ");
}
if (sbData.length() <= 3) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
// Construct new "Cookie:" line in request header,
// based on cookieParams
public void setCookieParams(TreeSet<HtmlParameter> cookieParams) {
if (cookieParams.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for (HtmlParameter parameter : cookieParams) {
if (parameter.getType() != HtmlParameter.Type.cookie) {
continue;
}
sbData.append(parameter.getName());
sbData.append('=');
sbData.append(parameter.getValue());
sbData.append("; ");
}
if (sbData.length() <= 3) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
public TreeSet<HtmlParameter> getCookieParams() {
TreeSet<HtmlParameter> set = new TreeSet<>();
Vector<String> cookieLines = getHeaders(HttpHeader.COOKIE);
if (cookieLines != null) {
for (String cookieLine : cookieLines) {
if (cookieLine.toUpperCase().startsWith(HttpHeader.COOKIE.toUpperCase())) {
// HttpCookie wont parse lines starting with "Cookie:"
cookieLine = cookieLine.substring(HttpHeader.COOKIE.length() + 1);
}
// These can be comma separated type=value
String [] cookieArray = cookieLine.split(";");
for (String cookie : cookieArray) {
set.add(new HtmlParameter(cookie));
}
}
}
return set;
}
// ZAP: Added method for working directly with HttpCookie
/**
* Gets a list of the http cookies from this request Header.
*
* @return the http cookies
* @throws IllegalArgumentException if a problem is encountered while processing the "Cookie: " header line.
*/
public List<HttpCookie> getHttpCookies() {
List<HttpCookie> cookies = new LinkedList<>();
// Use getCookieParams to reduce the places we parse cookies
TreeSet<HtmlParameter> ts = getCookieParams();
Iterator<HtmlParameter> it = ts.iterator();
while (it.hasNext()) {
HtmlParameter htmlParameter = it.next();
if(!htmlParameter.getName().isEmpty()) {
cookies.add(new HttpCookie(htmlParameter.getName(), htmlParameter.getValue()));
}
}
return cookies;
}
} | src/org/parosproxy/paros/network/HttpRequestHeader.java | /*
* Created on Jun 14, 2004
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012:02/01 Changed getHostPort() to return proper port number even if it
// is not explicitly specified in URI
// ZAP: 2011/08/04 Changed to support Logging
// ZAP: 2011/10/29 Log errors
// ZAP: 2011/11/03 Changed isImage() to prevent a NullPointerException when the path doesn't exist
// ZAP: 2011/12/09 Changed HttpRequestHeader(String method, URI uri, String version) to add
// the Cache-Control header field when the HTTP version is 1.1 and changed a if condition to
// validate the variable version instead of the variable method.
// ZAP: 2012/03/15 Changed to use the class StringBuilder instead of StringBuffer. Reworked some methods.
// ZAP: 2012/04/23 Added @Override annotation to all appropriate methods.
// ZAP: 2012/06/24 Added method to add Cookies of type java.net.HttpCookie to request header
// ZAP: 2012/06/24 Added new method of getting cookies from the request header.
// ZAP: 2012/10/08 Issue 361: getHostPort on HttpRequestHeader for HTTPS CONNECT
// requests returns the wrong port
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/03/08 Improved parse error reporting
package org.parosproxy.paros.network;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.log4j.Logger;
public class HttpRequestHeader extends HttpHeader {
private static final long serialVersionUID = 4156598327921777493L;
private static final Logger log = Logger.getLogger(HttpRequestHeader.class);
// method list
public final static String OPTIONS = "OPTIONS";
public final static String GET = "GET";
public final static String HEAD = "HEAD";
public final static String POST = "POST";
public final static String PUT = "PUT";
public final static String DELETE = "DELETE";
public final static String TRACE = "TRACE";
public final static String CONNECT = "CONNECT";
// ZAP: Added method array
public final static String[] METHODS = {OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT};
public final static String HOST = "Host";
private static final Pattern patternRequestLine = Pattern.compile(p_METHOD + p_SP + p_URI + p_SP + p_VERSION, Pattern.CASE_INSENSITIVE);
// private static final Pattern patternHostHeader
// = Pattern.compile("([^:]+)\\s*?:?\\s*?(\\d*?)");
private static final Pattern patternImage = Pattern.compile("\\.(bmp|ico|jpg|jpeg|gif|tiff|tif|png)\\z", Pattern.CASE_INSENSITIVE);
private static final Pattern patternPartialRequestLine = Pattern.compile("\\A *(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT)\\b", Pattern.CASE_INSENSITIVE);
private String mMethod = "";
private URI mUri = null;
private String mHostName = "";
/**
* The host port number of this request message, a non-negative integer.
* <p>
* <strong>Note:</strong> All the modifications to the instance variable
* {@code mHostPort} must be done through the method
* {@code setHostPort(int)}, so a valid and correct value is set when no
* port number is defined (which is represented with the negative integer
* -1).
* </p>
*
* @see #getHostPort()
* @see #setHostPort(int)
* @see URI#getPort()
*/
private int mHostPort;
private boolean mIsSecure = false;
/**
* Constructor for an empty header.
*
*/
public HttpRequestHeader() {
clear();
}
/**
* Constructor of a request header with the string.
*
* @param data
* @param isSecure If this request header is secure. URL will be converted
* to HTTPS if secure = true.
* @throws HttpMalformedHeaderException
*/
public HttpRequestHeader(String data, boolean isSecure) throws HttpMalformedHeaderException {
this();
setMessage(data, isSecure);
}
/**
* Constructor of a request header with the string. Whether this is a secure
* header depends on the URL given.
*
* @param data
* @throws HttpMalformedHeaderException
*/
public HttpRequestHeader(String data) throws HttpMalformedHeaderException {
this();
setMessage(data);
}
@Override
public void clear() {
super.clear();
mMethod = "";
mUri = null;
mHostName = "";
setHostPort(-1);
mMsgHeader = "";
}
public HttpRequestHeader(String method, URI uri, String version) throws HttpMalformedHeaderException {
this(method + " " + uri.toString() + " " + version.toUpperCase() + CRLF + CRLF);
try {
setHeader(HOST, uri.getHost() + (uri.getPort() > 0 ? ":" + Integer.toString(uri.getPort()) : ""));
} catch (URIException e) {
log.error(e.getMessage(), e);
}
setHeader(USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;)");
setHeader(PRAGMA, "no-cache");
// ZAP: added the Cache-Control header field to comply with HTTP/1.1
if (version.equalsIgnoreCase(HTTP11)) {
setHeader(CACHE_CONTROL, "no-cache");
}
setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded");
setHeader(ACCEPT_ENCODING, null);
// ZAP: changed from method to version
if (version.equalsIgnoreCase(HTTP11)) {
setContentLength(0);
}
}
/**
* Set this request header with the given message.
*
* @param data
* @param isSecure If this request header is secure. URL will be converted
* to HTTPS if secure = true.
* @throws HttpMalformedHeaderException
*/
public void setMessage(String data, boolean isSecure) throws HttpMalformedHeaderException {
super.setMessage(data);
try {
parse(isSecure);
} catch (HttpMalformedHeaderException e) {
mMalformedHeader = true;
if (log.isDebugEnabled()) {
log.debug("Malformed header: " + data, e);
}
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
mMalformedHeader = true;
throw new HttpMalformedHeaderException(e.getMessage());
}
}
/**
* Set this request header with the given message. Whether this is a secure
* header depends on the URL given.
*/
@Override
public void setMessage(String data) throws HttpMalformedHeaderException {
this.setMessage(data, false);
}
/**
* Get the HTTP method (GET, POST ... etc).
*
* @return
*/
public String getMethod() {
return mMethod;
}
/**
* Set the HTTP method of this request header.
*
* @param method
*/
public void setMethod(String method) {
mMethod = method.toUpperCase();
}
/**
* Get the URI of this request header.
*
* @return
*/
public URI getURI() {
return mUri;
}
/**
* Set the URI of this request header.
*
* @param uri
* @throws URIException
* @throws NullPointerException
*/
public void setURI(URI uri) throws URIException, NullPointerException {
if (uri.getScheme() == null || uri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + "/" + mUri.toString(), true);
} else {
mUri = uri;
}
if (uri.getScheme().equalsIgnoreCase(HTTPS)) {
mIsSecure = true;
} else {
mIsSecure = false;
}
setHostPort(mUri.getPort());
}
/**
* Get if this request header is under secure connection.
*
* @return
*/
public boolean getSecure() {
return mIsSecure;
}
/**
* Set if this request header is under secure connection.
*
* @param isSecure
* @throws URIException
* @throws NullPointerException
*/
public void setSecure(boolean isSecure) throws URIException, NullPointerException {
mIsSecure = isSecure;
if (mUri == null) {
// mUri not yet set
return;
}
URI newUri = mUri;
// check if URI consistent
if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
newUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
} else if (!getSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) {
newUri = new URI(mUri.toString().replaceFirst(HTTPS, HTTP), true);
}
if (newUri != mUri) {
mUri = newUri;
setHostPort(mUri.getPort());
}
}
/**
* Set the HTTP version of this request header.
*/
@Override
public void setVersion(String version) {
mVersion = version.toUpperCase();
}
/**
* Get the content length in this request header. If the content length is
* undetermined, 0 will be returned.
*/
@Override
public int getContentLength() {
if (mContentLength == -1) {
return 0;
}
return mContentLength;
}
/**
* Parse this request header.
*
* @param isSecure
* @return
* @throws URIException
* @throws NullPointerException
*/
private void parse(boolean isSecure) throws URIException, HttpMalformedHeaderException {
mIsSecure = isSecure;
Matcher matcher = patternRequestLine.matcher(mStartLine);
if (!matcher.find()) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException("Failed to find pattern: " + patternRequestLine);
}
mMethod = matcher.group(1);
String sUri = matcher.group(2);
mVersion = matcher.group(3);
if (!mVersion.equalsIgnoreCase(HTTP09) && !mVersion.equalsIgnoreCase(HTTP10) && !mVersion.equalsIgnoreCase(HTTP11)) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException("Unexpected version: " + mVersion);
}
mUri = parseURI(sUri);
if (mUri.getScheme() == null || mUri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true);
}
if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
}
if (mUri.getScheme().equalsIgnoreCase(HTTPS)) {
setSecure(true);
}
String hostHeader = null;
if (mMethod.equalsIgnoreCase(CONNECT)) {
hostHeader = sUri;
parseHostName(hostHeader);
} else {
mHostName = mUri.getHost();
setHostPort(mUri.getPort());
}
}
private void parseHostName(String hostHeader) {
// no host header given but a valid host name already exist.
if (hostHeader == null) {
return;
}
int port = -1;
int pos = 0;
if ((pos = hostHeader.indexOf(':', 2)) > -1) {
mHostName = hostHeader.substring(0, pos).trim();
try {
port = Integer.parseInt(hostHeader.substring(pos + 1));
} catch (NumberFormatException e) {
}
} else {
mHostName = hostHeader.trim();
}
setHostPort(port);
}
/**
* Get the host name in this request header.
*
* @return Host name.
*/
public String getHostName() {
String hostName = mHostName;
try {
// ZAP: fixed cases, where host name is null
hostName = ((mUri.getHost() != null) ? mUri.getHost() : mHostName);
} catch (URIException e) {
if (log.isDebugEnabled()) {
log.warn(e);
}
}
return hostName;
}
/**
* Gets the host port number of this request message, a non-negative
* integer.
* <p>
* If no port is defined the default port for the used scheme will be
* returned, either 80 for HTTP or 443 for HTTPS.
* </p>
*
* @return the host port number, a non-negative integer
*/
public int getHostPort() {
return mHostPort;
}
/**
* Sets the host port number of this request message.
* <p>
* If the given {@code port} number is negative (usually -1 to represent
* that no port number is defined), the port number set will be the default
* port number for the used scheme known using the method
* {@code getSecure()}, either 80 for HTTP or 443 for HTTPS.
* </p>
*
* @param port
* the new port number
* @see #mHostPort
* @see #getSecure()
* @see URI#getPort()
*/
private void setHostPort(int port) {
if (port > -1) {
mHostPort = port;
} else if (this.getSecure()) {
mHostPort = 443;
} else {
mHostPort = 80;
}
}
/**
* Return if this request header is a image request basing on the path
* suffix.
*/
@Override
public boolean isImage() {
try {
// ZAP: prevents a NullPointerException when no path exists
final String path = getURI().getPath();
if (path != null) {
return (patternImage.matcher(path).find());
}
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return false;
}
/**
* Return if the data given is a request header basing on the first start
* line.
*
* @param data
* @return
*/
public static boolean isRequestLine(String data) {
return patternPartialRequestLine.matcher(data).find();
}
/**
* Return the prime header (first line).
*/
@Override
public String getPrimeHeader() {
return getMethod() + " " + getURI().toString() + " " + getVersion();
}
/*
* private static final char[] DELIM_UNWISE_CHAR = { '<', '>', '#', '"', '
* ', '{', '}', '|', '\\', '^', '[', ']', '`' };
*/
private static final String DELIM = "<>#\"";
private static final String UNWISE = "{}|\\^[]`";
private static final String DELIM_UNWISE = DELIM + UNWISE;
public static URI parseURI(String sUri) throws URIException {
URI uri = null;
int len = sUri.length();
StringBuilder sb = new StringBuilder(len);
char[] charray = new char[1];
String s = null;
for (int i = 0; i < len; i++) {
char ch = sUri.charAt(i);
//String ch = sUri.substring(i, i+1);
if (DELIM_UNWISE.indexOf(ch) >= 0) {
// check if unwise or delim in RFC. If so, encode it.
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
} else if (ch == '%') {
// % is exception - no encoding to be done because some server may not handle
// correctly when % is invalid.
//
//sb.append(ch);
// if % followed by hex, no encode.
try {
String hex = sUri.substring(i + 1, i + 3);
Integer.parseInt(hex, 16);
sb.append(ch);
} catch (Exception e) {
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
}
} else if (ch == ' ') {
// if URLencode, '+' will be appended.
sb.append("%20");
} else {
sb.append(ch);
}
}
uri = new URI(sb.toString(), true);
return uri;
}
// Construct new GET url of request
// Based on getParams
public void setGetParams(TreeSet<HtmlParameter> getParams) {
if (mUri == null) {
return;
}
if (getParams.isEmpty()) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
StringBuilder sbQuery = new StringBuilder();
for (HtmlParameter parameter : getParams) {
if (parameter.getType() != HtmlParameter.Type.url) {
continue;
}
sbQuery.append(parameter.getName());
sbQuery.append('=');
sbQuery.append(parameter.getValue());
sbQuery.append('&');
}
if (sbQuery.length() <= 2) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
String query = sbQuery.substring(0, sbQuery.length() - 1);
try {
//The previous behaviour was escaping the query,
//so it is maintained with the use of setQuery.
mUri.setQuery(query);
} catch (URIException e) {
log.error(e.getMessage(), e);
}
}
/**
* Construct new "Cookie:" line in request header based on HttpCookies.
*
* @param cookies the new cookies
*/
public void setCookies(List<HttpCookie> cookies) {
if (cookies.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for(HttpCookie c:cookies){
sbData.append(c.getName());
sbData.append('=');
sbData.append(c.getValue());
sbData.append("; ");
}
if (sbData.length() <= 3) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
// Construct new "Cookie:" line in request header,
// based on cookieParams
public void setCookieParams(TreeSet<HtmlParameter> cookieParams) {
if (cookieParams.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for (HtmlParameter parameter : cookieParams) {
if (parameter.getType() != HtmlParameter.Type.cookie) {
continue;
}
sbData.append(parameter.getName());
sbData.append('=');
sbData.append(parameter.getValue());
sbData.append("; ");
}
if (sbData.length() <= 3) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
public TreeSet<HtmlParameter> getCookieParams() {
TreeSet<HtmlParameter> set = new TreeSet<>();
Vector<String> cookieLines = getHeaders(HttpHeader.COOKIE);
if (cookieLines != null) {
for (String cookieLine : cookieLines) {
if (cookieLine.toUpperCase().startsWith(HttpHeader.COOKIE.toUpperCase())) {
// HttpCookie wont parse lines starting with "Cookie:"
cookieLine = cookieLine.substring(HttpHeader.COOKIE.length() + 1);
}
// These can be comma separated type=value
String [] cookieArray = cookieLine.split(";");
for (String cookie : cookieArray) {
set.add(new HtmlParameter(cookie));
}
}
}
return set;
}
// ZAP: Added method for working directly with HttpCookie
/**
* Gets a list of the http cookies from this request Header.
*
* @return the http cookies
* @throws IllegalArgumentException if a problem is encountered while processing the "Cookie: " header line.
*/
public List<HttpCookie> getHttpCookies() {
List<HttpCookie> cookies = new LinkedList<>();
// Use getCookieParams to reduce the places we parse cookies
TreeSet<HtmlParameter> ts = getCookieParams();
Iterator<HtmlParameter> it = ts.iterator();
while (it.hasNext()) {
HtmlParameter htmlParameter = it.next();
if(!htmlParameter.getName().isEmpty()) {
cookies.add(new HttpCookie(htmlParameter.getName(), htmlParameter.getValue()));
}
}
return cookies;
}
} | Issue 596 - Rename the method HttpRequestHeader.getSecure to isSecure
- Added a new method HttpRequestHeader.isSecure;
- Deprecated the old method (HttpRequestHeader.getSecure);
- Replaced all calls to the old method with the new method.
| src/org/parosproxy/paros/network/HttpRequestHeader.java | Issue 596 - Rename the method HttpRequestHeader.getSecure to isSecure | <ide><path>rc/org/parosproxy/paros/network/HttpRequestHeader.java
<ide> // requests returns the wrong port
<ide> // ZAP: 2013/01/23 Clean up of exception handling/logging.
<ide> // ZAP: 2013/03/08 Improved parse error reporting
<add>// ZAP: 2013/04/14 Issue 596: Rename the method HttpRequestHeader.getSecure to isSecure
<ide>
<ide> package org.parosproxy.paros.network;
<ide>
<ide> * Get if this request header is under secure connection.
<ide> *
<ide> * @return
<del> */
<add> * @deprecated Replaced by {@link #isSecure()}. It will be removed in a future release.
<add> */
<add> @Deprecated
<ide> public boolean getSecure() {
<add> return mIsSecure;
<add> }
<add>
<add> /**
<add> * Tells whether the request is secure, or not. A request is considered secure if it's using the HTTPS protocol.
<add> *
<add> * @return {@code true} if the request is secure, {@code false} otherwise.
<add> */
<add> public boolean isSecure() {
<ide> return mIsSecure;
<ide> }
<ide>
<ide>
<ide> URI newUri = mUri;
<ide> // check if URI consistent
<del> if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
<add> if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
<ide> newUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
<del> } else if (!getSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) {
<add> } else if (!isSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) {
<ide> newUri = new URI(mUri.toString().replaceFirst(HTTPS, HTTP), true);
<ide> }
<ide>
<ide> mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true);
<ide> }
<ide>
<del> if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
<add> if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
<ide> mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
<ide> }
<ide>
<ide> * If the given {@code port} number is negative (usually -1 to represent
<ide> * that no port number is defined), the port number set will be the default
<ide> * port number for the used scheme known using the method
<del> * {@code getSecure()}, either 80 for HTTP or 443 for HTTPS.
<add> * {@code isSecure()}, either 80 for HTTP or 443 for HTTPS.
<ide> * </p>
<ide> *
<ide> * @param port
<ide> * the new port number
<ide> * @see #mHostPort
<del> * @see #getSecure()
<add> * @see #isSecure()
<ide> * @see URI#getPort()
<ide> */
<ide> private void setHostPort(int port) {
<ide> if (port > -1) {
<ide> mHostPort = port;
<del> } else if (this.getSecure()) {
<add> } else if (this.isSecure()) {
<ide> mHostPort = 443;
<ide> } else {
<ide> mHostPort = 80; |
|
JavaScript | mit | 094c4e68451e73cfbffbf925cc6996b5c9a9faf9 | 0 | folksy-squid/Picky-Notes,inspiredtolive/Picky-Notes,derektliu/Picky-Notes,folksy-squid/Picky-Notes,derektliu/Picky-Notes,inspiredtolive/Picky-Notes,folksy-squid/Picky-Notes,inspiredtolive/Picky-Notes,derektliu/Picky-Notes | const Sequelize = require('sequelize');
const db = new Sequelize('postgres://ubuntu:password@localhost:5432/pickynotes', { logging: false });
const {User} = require('./controllers/UserController')(db, Sequelize);
const {Room} = require('./controllers/RoomController')(db, Sequelize);
const {Note} = require('./controllers/NoteController')(db, Sequelize);
Room.belongsTo(User, {foreignKey: 'hostId', as: 'host', constraints: false});
User.belongsToMany(Room, {foreignKey: 'lectureRoomId', through: 'UserRoom'});
Room.belongsToMany(User, {foreignKey: 'studentId', through: 'UserRoom'});
Room.hasMany(Note, {as: 'notes'});
Note.belongsTo(Room, {as: 'room', onDelete: 'cascade'});
Note.belongsTo(User, {foreignKey: 'editingUserId', as: 'editingUser', onDelete: 'cascade'});
Note.belongsTo(User, {foreignKey: 'originalUserId', as: 'originalUser'});
// db.sync()
// .then(
// User.create({
// facebookId: '10206128224638462',
// name: 'Kunal Rathi',
// email: '[email protected]',
// pictureUrl: 'https://scontent-sjc2-1.xx.fbcdn.net/v/t1.0-1/p320x320/735019_3760102334957_1830986009_n.jpg?oh=95f952f6a491fa054cbb85122e45395f&oe=587471E6',
// gender: 'Male'
// })
// .then((user) => {
// Room.create({
// pathUrl: 'awBzD',
// })
// .then((room) => {
// Note.create({
// content: 'a note',
// audioTimestamp: new Date()
// })
// .then((note) => {
// note.setOriginalUser(user);
// note.setEditingUser(user);
// room.setHost(user);
// room.addNote(note);
// });
// });
// })
// .catch((err) => {
// console.log(err);
// }));
module.exports = {db, User, Room, Note};
| server/database/db-config.js | const Sequelize = require('sequelize');
const db = new Sequelize('postgres://ubuntu:password@localhost:5432/pickynotes', { logging: false });
const {User} = require('./controllers/UserController')(db, Sequelize);
const {Room} = require('./controllers/RoomController')(db, Sequelize, User);
const {Note} = require('./controllers/NoteController')(db, Sequelize, User);
Room.belongsTo(User, {foreignKey: 'hostId', as: 'host', constraints: false});
User.belongsToMany(Room, {foreignKey: 'lectureRoomId', as: 'lectureRooms', through: 'UserRoom'});
Room.belongsToMany(User, {foreignKey: 'studentId', as: 'students', through: 'UserRoom'});
Room.hasMany(Note, {as: 'notes'});
Note.belongsTo(Room, {as: 'room', onDelete: 'cascade'});
Note.belongsTo(User, {foreignKey: 'editingUserId', as: 'editingUser', onDelete: 'cascade'});
Note.belongsTo(User, {foreignKey: 'originalUserId', as: 'originalUser'});
// db.sync()
// .then(
// User.create({
// facebookId: '10206128224638462',
// name: 'Kunal Rathi',
// email: '[email protected]',
// pictureUrl: 'https://scontent-sjc2-1.xx.fbcdn.net/v/t1.0-1/p320x320/735019_3760102334957_1830986009_n.jpg?oh=95f952f6a491fa054cbb85122e45395f&oe=587471E6',
// gender: 'Male'
// })
// .then((user) => {
// Room.create({
// pathUrl: 'awBzD',
// })
// .then((room) => {
// Note.create({
// content: 'a note',
// audioTimestamp: new Date()
// })
// .then((note) => {
// note.setOriginalUser(user);
// note.setEditingUser(user);
// room.setHost(user);
// room.addNote(note);
// });
// });
// })
// .catch((err) => {
// console.log(err);
// }));
module.exports = {db, User, Room, Note};
| Update db-config.js | server/database/db-config.js | Update db-config.js | <ide><path>erver/database/db-config.js
<ide> const db = new Sequelize('postgres://ubuntu:password@localhost:5432/pickynotes', { logging: false });
<ide>
<ide> const {User} = require('./controllers/UserController')(db, Sequelize);
<del>const {Room} = require('./controllers/RoomController')(db, Sequelize, User);
<del>const {Note} = require('./controllers/NoteController')(db, Sequelize, User);
<add>const {Room} = require('./controllers/RoomController')(db, Sequelize);
<add>const {Note} = require('./controllers/NoteController')(db, Sequelize);
<ide>
<ide> Room.belongsTo(User, {foreignKey: 'hostId', as: 'host', constraints: false});
<ide>
<del>User.belongsToMany(Room, {foreignKey: 'lectureRoomId', as: 'lectureRooms', through: 'UserRoom'});
<del>Room.belongsToMany(User, {foreignKey: 'studentId', as: 'students', through: 'UserRoom'});
<add>User.belongsToMany(Room, {foreignKey: 'lectureRoomId', through: 'UserRoom'});
<add>Room.belongsToMany(User, {foreignKey: 'studentId', through: 'UserRoom'});
<ide>
<ide> Room.hasMany(Note, {as: 'notes'});
<ide> Note.belongsTo(Room, {as: 'room', onDelete: 'cascade'}); |
|
Java | mit | error: pathspec 'src/codingbat/logic1/AlarmClockTest.java' did not match any file(s) known to git
| af95989b7f16f1868dc16304a85e3c95b36b29aa | 1 | raeffu/codingbat | package codingbat.logic1;
// Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat,
// and a boolean indicating if we are on vacation,
// return a string of the form "7:00" indicating when the alarm clock should ring.
// Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00".
// Unless we are on vacation -- then on weekdays it should be "10:00"
// and weekends it should be "off".
//
// alarmClock(1, false) = "7:00"
// alarmClock(5, false) = "7:00"
// alarmClock(0, false) = "10:00"
public class AlarmClockTest {
public static void main(String[] args) {
AlarmClockTest test = new AlarmClockTest();
System.out.println(">" + test.alarmClock(1, false) + "<");
System.out.println(">" + test.alarmClock(5, false) + "<");
System.out.println(">" + test.alarmClock(0, false) + "<");
}
public String alarmClock(int day, boolean vacation) {
String early = "7:00";
String late = "10:00";
String off = "off";
if (day == 0 || day == 6) {
if (vacation) {
return off;
}
return late;
}
else if (vacation) {
return late;
}
return early;
}
}
| src/codingbat/logic1/AlarmClockTest.java | add alarmClock task | src/codingbat/logic1/AlarmClockTest.java | add alarmClock task | <ide><path>rc/codingbat/logic1/AlarmClockTest.java
<add>package codingbat.logic1;
<add>
<add>// Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat,
<add>// and a boolean indicating if we are on vacation,
<add>// return a string of the form "7:00" indicating when the alarm clock should ring.
<add>// Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00".
<add>// Unless we are on vacation -- then on weekdays it should be "10:00"
<add>// and weekends it should be "off".
<add>//
<add>// alarmClock(1, false) = "7:00"
<add>// alarmClock(5, false) = "7:00"
<add>// alarmClock(0, false) = "10:00"
<add>
<add>public class AlarmClockTest {
<add>
<add> public static void main(String[] args) {
<add> AlarmClockTest test = new AlarmClockTest();
<add>
<add> System.out.println(">" + test.alarmClock(1, false) + "<");
<add> System.out.println(">" + test.alarmClock(5, false) + "<");
<add> System.out.println(">" + test.alarmClock(0, false) + "<");
<add> }
<add>
<add> public String alarmClock(int day, boolean vacation) {
<add> String early = "7:00";
<add> String late = "10:00";
<add> String off = "off";
<add>
<add> if (day == 0 || day == 6) {
<add> if (vacation) {
<add> return off;
<add> }
<add> return late;
<add> }
<add> else if (vacation) {
<add> return late;
<add> }
<add> return early;
<add> }
<add>
<add>} |
|
JavaScript | mit | 1997b760a0ca2c29336f107bb0854fac38ca8396 | 0 | IonicaBizau/node-lazy-api | // Dependencies
var LazyApi = require("../lib");
var Apis = {};
// Instead of doing
// Apis.some = require("./some");
// we do:
LazyApi(Apis, "some", __dirname + "/some");
// And when we will call this method, the file
// will be loaded in the RAM.
Apis.some.method({foo: "bar"}, function (err, d) {
console.log(err || d);
});
// What if we need to run some custom handlers?
LazyApi.returnHandler = function (path, name, scope) {
console.log("Loading " + path);
return require(path);
};
// "Load" (but not in RAM) the another file
LazyApi(Apis, "another", __dirname + "/another");
// Call the method (this will load the file)
Apis.another.method({foo: "bar"}, function (err, d) {
console.log(err || d);
});
// Call the method again (the file is already loaded);
Apis.another.method({foo: "bar"}, function (err, d) {
console.log(err || d);
});
| test/index.js | // Dependencies
var LazyApi = require("../lib");
var Apis = {};
// Instead of doing
// Apis.some = require("./some");
// we do:
LazyApi(Apis, "some", __dirname + "/some");
// And when we will call this method, the file
// will be loaded in the RAM.
Apis.some.method({foo: "bar"}, function (err, d) {
console.log(err || d);
});
// What if we need to run some custom handlers?
LazyApi.returnHandler = function (path, name, scope) {
console.log("Loading " + path);
return require(path);
};
// "Load" (but not in RAM) the another file
LazyApi(Apis, "another", __dirname + "/another");
// Call the method (this will load the file)
Apis.another.method({foo: "bar"}, function (err, d) {
console.log(err || d);
});
| Call again the API
| test/index.js | Call again the API | <ide><path>est/index.js
<ide> Apis.another.method({foo: "bar"}, function (err, d) {
<ide> console.log(err || d);
<ide> });
<add>
<add>// Call the method again (the file is already loaded);
<add>Apis.another.method({foo: "bar"}, function (err, d) {
<add> console.log(err || d);
<add>}); |
|
Java | apache-2.0 | 97298c5da3f91ddc064fe3131d05ca6cb89fbee7 | 0 | TomK/closure-compiler,vrkansagara/closure-compiler,mbebenita/closure-compiler,visokio/closure-compiler,mediogre/closure-compiler,nicks/closure-compiler-old,jaen/closure-compiler,maio/closure-compiler,mediogre/closure-compiler,rockyzh/closure-compiler,fvigotti/closure-compiler,vobruba-martin/closure-compiler,rockyzh/closure-compiler,brad4d/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,ralic/closure-compiler,lgeorgieff/closure-compiler,visokio/closure-compiler,nawawi/closure-compiler,dushmis/closure-compiler,GerHobbelt/closure-compiler,rintaro/closure-compiler,robbert/closure-compiler,shantanusharma/closure-compiler,mbebenita/closure-compiler,robbert/closure-compiler-copy,pauldraper/closure-compiler,jimmytuc/closure-compiler,tdelmas/closure-compiler,thurday/closure-compiler,anomaly/closure-compiler,mbebenita/closure-compiler,tiobe/closure-compiler,phistuck/closure-compiler,vobruba-martin/closure-compiler,mweissbacher/closure-compiler,savelichalex/closure-compiler,dlochrie/closure-compiler,nawawi/closure-compiler,dushmis/closure-compiler,jimmytuc/closure-compiler,leapingbrainlabs/closure-compiler,ochafik/closure-compiler,anneupsc/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,Dominator008/closure-compiler,vrkansagara/closure-compiler,tsdl2013/closure-compiler,shantanusharma/closure-compiler,BladeRunnerJS/closure-compiler,MatrixFrog/closure-compiler,nawawi/closure-compiler,anneupsc/closure-compiler,fvigotti/closure-compiler,Pimm/closure-compiler,savelichalex/closure-compiler,superkonduktr/closure-compiler,anomaly/closure-compiler,ochafik/closure-compiler,tiobe/closure-compiler,mbrukman/closure-compiler,MatrixFrog/closure-compiler,vobruba-martin/closure-compiler,tntim96/closure-compiler,brad4d/closure-compiler,tiobe/closure-compiler,grpbwl/closure-compiler,weiwl/closure-compiler,ChadKillingsworth/closure-compiler,tiobe/closure-compiler,tdelmas/closure-compiler,google/closure-compiler,ksheedlo/closure-compiler,grpbwl/closure-compiler,google/closure-compiler,mweissbacher/closure-compiler,vrkansagara/closure-compiler,SkReD/closure-compiler,redforks/closure-compiler,robbert/closure-compiler,rintaro/closure-compiler,jimmytuc/closure-compiler,anomaly/closure-compiler,anomaly/closure-compiler,monetate/closure-compiler,ochafik/closure-compiler,knutwalker/google-closure-compiler,ChadKillingsworth/closure-compiler,SkReD/closure-compiler,lgeorgieff/closure-compiler,visokio/closure-compiler,fvigotti/closure-compiler,weiwl/closure-compiler,mneise/closure-compiler,mprobst/closure-compiler,Yannic/closure-compiler,pr4v33n/closure-compiler,Yannic/closure-compiler,knutwalker/google-closure-compiler,leapingbrainlabs/closure-compiler,BladeRunnerJS/closure-compiler,ChadKillingsworth/closure-compiler,superkonduktr/closure-compiler,pauldraper/closure-compiler,grpbwl/closure-compiler,concavelenz/closure-compiler,tsdl2013/closure-compiler,superkonduktr/closure-compiler,pr4v33n/closure-compiler,monetate/closure-compiler,rintaro/closure-compiler,LorenzoDV/closure-compiler,tdelmas/closure-compiler,mweissbacher/closure-compiler,weiwl/closure-compiler,ChadKillingsworth/closure-compiler,concavelenz/closure-compiler,nicupavel/google-closure-compiler,dlochrie/closure-compiler,Medium/closure-compiler,neraliu/closure-compiler,Pimm/closure-compiler,dushmis/closure-compiler,dlochrie/closure-compiler,MatrixFrog/closure-compiler,Medium/closure-compiler,Pimm/closure-compiler,mbrukman/closure-compiler,selkhateeb/closure-compiler,Dominator008/closure-compiler,nawawi/closure-compiler,mneise/closure-compiler,GerHobbelt/closure-compiler,lgeorgieff/closure-compiler,tsdl2013/closure-compiler,maio/closure-compiler,shantanusharma/closure-compiler,mneise/closure-compiler,thurday/closure-compiler,maio/closure-compiler,mcanthony/closure-compiler,jhiswin/idiil-closure-compiler,robbert/closure-compiler-copy,selkhateeb/closure-compiler,tdelmas/closure-compiler,pr4v33n/closure-compiler,martinrosstmc/closure-compiler,phistuck/closure-compiler,GerHobbelt/closure-compiler,mprobst/closure-compiler,wenzowski/closure-compiler,neraliu/closure-compiler,tntim96/closure-compiler,nicupavel/google-closure-compiler,vobruba-martin/closure-compiler,google/closure-compiler,brad4d/closure-compiler,GerHobbelt/closure-compiler,mbrukman/closure-compiler,BladeRunnerJS/closure-compiler,nicks/closure-compiler-old,wenzowski/closure-compiler,redforks/closure-compiler,LorenzoDV/closure-compiler,mprobst/closure-compiler,mediogre/closure-compiler,rockyzh/closure-compiler,savelichalex/closure-compiler,mweissbacher/closure-compiler,neraliu/closure-compiler,ralic/closure-compiler,mprobst/closure-compiler,tntim96/closure-compiler,concavelenz/closure-compiler,ralic/closure-compiler,thurday/closure-compiler,Yannic/closure-compiler,SkReD/closure-compiler,Dominator008/closure-compiler,jaen/closure-compiler,selkhateeb/closure-compiler,monetate/closure-compiler,google/closure-compiler,Medium/closure-compiler,martinrosstmc/closure-compiler,phistuck/closure-compiler,superkonduktr/closure-compiler,TomK/closure-compiler,TomK/closure-compiler,redforks/closure-compiler,jhiswin/idiil-closure-compiler,ksheedlo/closure-compiler,jaen/closure-compiler,anneupsc/closure-compiler,mcanthony/closure-compiler,mcanthony/closure-compiler,LorenzoDV/closure-compiler,lgeorgieff/closure-compiler,pauldraper/closure-compiler | /*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.graph.GraphReachability;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Removes dead code from a parse tree. The kinds of dead code that this pass
* removes are:
* - Any code following a return statement, such as the <code>alert</code>
* call in: <code>if (x) { return; alert('unreachable'); }</code>.
* - Statements that have no side effects, such as:
* <code>a.b.MyClass.prototype.propertyName;</code> or <code>true;</code>.
* That first kind of statement sometimes appears intentionally, so that
* prototype properties can be annotated using JSDoc without actually
* being initialized.
*
*/
// TODO(user): Besides dead code after returns, this pass removes useless live
// code such as breaks/continues/returns and stms w/out side effects.
// These things don't require reachability info, consider making them their own
// pass or putting them in some other, more related pass.
class UnreachableCodeElimination extends AbstractPostOrderCallback
implements CompilerPass, ScopedCallback {
private static final Logger logger =
Logger.getLogger(UnreachableCodeElimination.class.getName());
private final AbstractCompiler compiler;
private final boolean removeNoOpStatements;
private boolean codeChanged;
UnreachableCodeElimination(AbstractCompiler compiler,
boolean removeNoOpStatements) {
this.compiler = compiler;
this.removeNoOpStatements = removeNoOpStatements;
}
@Override
public void exitScope(NodeTraversal t) {
Scope scope = t.getScope();
Node root = scope.getRootNode();
// Computes the control flow graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, root);
ControlFlowGraph<Node> cfg = cfa.getCfg();
new GraphReachability<Node, ControlFlowGraph.Branch>(cfg)
.compute(cfg.getEntry().getValue());
if (scope.isLocal()) {
root = root.getLastChild();
}
do {
codeChanged = false;
NodeTraversal.traverse(compiler, root, new EliminationPass(cfg));
} while (codeChanged);
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
}
private class EliminationPass extends AbstractShallowCallback {
private final ControlFlowGraph<Node> cfg;
private EliminationPass(ControlFlowGraph<Node> cfg) {
this.cfg = cfg;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (parent == null || n.isFunction() || n.isScript()) {
return;
}
DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
if (gNode == null) { // Not in CFG.
return;
}
if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
(removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
removeDeadExprStatementSafely(n);
return;
}
tryRemoveUnconditionalBranching(n);
}
/**
* Tries to remove n if it is an unconditional branch node (break, continue,
* or return) and the target of n is the same as the the follow of n.
* That is, if removing n preserves the control flow. Also if n targets
* another unconditional branch, this function will recursively try to
* remove the target branch as well. The reason why we want to cascade this
* removal is because we only run this pass once. If we have code such as
*
* break -> break -> break
*
* where all 3 breaks are useless, then the order of removal matters. When
* we first look at the first break, we see that it branches to the 2nd
* break. However, if we remove the last break, the 2nd break becomes
* useless and finally the first break becomes useless as well.
*
* @returns The target of this jump. If the target is also useless jump,
* the target of that useless jump recursively.
*/
@SuppressWarnings("fallthrough")
private void tryRemoveUnconditionalBranching(Node n) {
/*
* For each unconditional branching control flow node, check to see
* if the ControlFlowAnalysis.computeFollowNode of that node is same as
* the branching target. If it is, the branch node is safe to be removed.
*
* This is not as clever as MinimizeExitPoints because it doesn't do any
* if-else conversion but it handles more complicated switch statements
* much more nicely.
*/
// If n is null the target is the end of the function, nothing to do.
if (n == null) {
return;
}
DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
if (gNode == null) {
return;
}
switch (n.getType()) {
case Token.RETURN:
if (n.hasChildren()) {
break;
}
case Token.BREAK:
case Token.CONTINUE:
// We are looking for a control flow changing statement that always
// branches to the same node. If after removing it control still
// branches to the same node, it is safe to remove.
List<DiGraphEdge<Node, Branch>> outEdges = gNode.getOutEdges();
if (outEdges.size() == 1 &&
// If there is a next node, this jump is not useless.
(n.getNext() == null || n.getNext().isFunction())) {
Preconditions.checkState(
outEdges.get(0).getValue() == Branch.UNCOND);
Node fallThrough = computeFollowing(n);
Node nextCfgNode = outEdges.get(0).getDestination().getValue();
if (nextCfgNode == fallThrough) {
removeNode(n);
}
}
}
}
private Node computeFollowing(Node n) {
Node next = ControlFlowAnalysis.computeFollowNode(n);
while (next != null && next.isBlock()) {
if (next.hasChildren()) {
next = next.getFirstChild();
} else {
next = computeFollowing(next);
}
}
return next;
}
private void removeDeadExprStatementSafely(Node n) {
Node parent = n.getParent();
if (n.isEmpty() || (n.isBlock() && !n.hasChildren())) {
// Not always trivial to remove, let FoldConstants work its magic later.
return;
}
// TODO(user): This is a problem with removeNoOpStatements.
// Every expression in a FOR-IN header looks side effect free on its own.
if (NodeUtil.isForIn(parent)) {
return;
}
switch (n.getType()) {
// Removing an unreachable DO node is messy b/c it means we still have
// to execute one iteration. If the DO's body has breaks in the middle,
// it can get even more tricky and code size might actually increase.
case Token.DO:
return;
case Token.BLOCK:
// BLOCKs are used in several ways including wrapping CATCH
// blocks in TRYs
if (parent.isTry() && NodeUtil.isTryCatchNodeContainer(n)) {
return;
}
break;
case Token.CATCH:
Node tryNode = parent.getParent();
NodeUtil.maybeAddFinally(tryNode);
break;
}
if (n.isVar() && !n.getFirstChild().hasChildren()) {
// Very unlikely case, Consider this:
// File 1: {throw 1}
// File 2: {var x}
// The node var x is unreachable in the global scope.
// Before we remove the node, redeclareVarsInsideBranch
// would basically move var x to the beginning of File 2,
// which resulted in zero changes to the AST but triggered
// reportCodeChange().
// Instead, we should just ignore dead variable declarations.
return;
}
removeNode(n);
}
private void removeNode(Node n) {
codeChanged = true;
NodeUtil.redeclareVarsInsideBranch(n);
compiler.reportCodeChange();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Removing " + n.toString());
}
NodeUtil.removeChild(n.getParent(), n);
}
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {}
@Override
public void enterScope(NodeTraversal t) {}
}
| src/com/google/javascript/jscomp/UnreachableCodeElimination.java | /*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.graph.GraphReachability;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Removes dead code from a parse tree. The kinds of dead code that this pass
* removes are:
* - Any code following a return statement, such as the <code>alert</code>
* call in: <code>if (x) { return; alert('unreachable'); }</code>.
* - Statements that have no side effects, such as:
* <code>a.b.MyClass.prototype.propertyName;</code> or <code>true;</code>.
* That first kind of statement sometimes appears intentionally, so that
* prototype properties can be annotated using JSDoc without actually
* being initialized.
*
*/
// TODO(user): Besides dead code after returns, this pass removes useless live
// code such as breaks/continues/returns and stms w/out side effects.
// These things don't require reachability info, consider making them their own
// pass or putting them in some other, more related pass.
class UnreachableCodeElimination extends AbstractPostOrderCallback
implements CompilerPass, ScopedCallback {
private static final Logger logger =
Logger.getLogger(UnreachableCodeElimination.class.getName());
private final AbstractCompiler compiler;
private final boolean removeNoOpStatements;
private boolean codeChanged;
UnreachableCodeElimination(AbstractCompiler compiler,
boolean removeNoOpStatements) {
this.compiler = compiler;
this.removeNoOpStatements = removeNoOpStatements;
}
@Override
public void exitScope(NodeTraversal t) {
Scope scope = t.getScope();
Node root = scope.getRootNode();
// Computes the control flow graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, root);
ControlFlowGraph<Node> cfg = cfa.getCfg();
new GraphReachability<Node, ControlFlowGraph.Branch>(cfg)
.compute(cfg.getEntry().getValue());
if (scope.isLocal()) {
root = root.getLastChild();
}
do {
codeChanged = false;
NodeTraversal.traverse(compiler, root, new EliminationPass(cfg));
} while (codeChanged);
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
}
private class EliminationPass extends AbstractShallowCallback {
private final ControlFlowGraph<Node> cfg;
private EliminationPass(ControlFlowGraph<Node> cfg) {
this.cfg = cfg;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (parent == null || n.isFunction() || n.isScript()) {
return;
}
DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
if (gNode == null) { // Not in CFG.
return;
}
if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
(removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
removeDeadExprStatementSafely(n);
return;
}
tryRemoveUnconditionalBranching(n);
}
/**
* Tries to remove n if it is an unconditional branch node (break, continue,
* or return) and the target of n is the same as the the follow of n.
* That is, if removing n preserves the control flow. Also if n targets
* another unconditional branch, this function will recursively try to
* remove the target branch as well. The reason why we want to cascade this
* removal is because we only run this pass once. If we have code such as
*
* break -> break -> break
*
* where all 3 breaks are useless, then the order of removal matters. When
* we first look at the first break, we see that it branches to the 2nd
* break. However, if we remove the last break, the 2nd break becomes
* useless and finally the first break becomes useless as well.
*
* @return The target of this jump. If the target is also useless jump,
* the target of that useless jump recursively.
*/
@SuppressWarnings("fallthrough")
private void tryRemoveUnconditionalBranching(Node n) {
/*
* For each unconditional branching control flow node, check to see
* if the ControlFlowAnalysis.computeFollowNode of that node is same as
* the branching target. If it is, the branch node is safe to be removed.
*
* This is not as clever as MinimizeExitPoints because it doesn't do any
* if-else conversion but it handles more complicated switch statements
* much more nicely.
*/
// If n is null the target is the end of the function, nothing to do.
if (n == null) {
return;
}
DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
if (gNode == null) {
return;
}
switch (n.getType()) {
case Token.RETURN:
if (n.hasChildren()) {
break;
}
case Token.BREAK:
case Token.CONTINUE:
// We are looking for a control flow changing statement that always
// branches to the same node. If after removing it control still
// branches to the same node, it is safe to remove.
List<DiGraphEdge<Node, Branch>> outEdges = gNode.getOutEdges();
if (outEdges.size() == 1 &&
// If there is a next node, this jump is not useless.
(n.getNext() == null || n.getNext().isFunction())) {
Preconditions.checkState(
outEdges.get(0).getValue() == Branch.UNCOND);
Node fallThrough = computeFollowing(n);
Node nextCfgNode = outEdges.get(0).getDestination().getValue();
if (nextCfgNode == fallThrough) {
removeNode(n);
}
}
}
}
private Node computeFollowing(Node n) {
Node next = ControlFlowAnalysis.computeFollowNode(n);
while (next != null && next.isBlock()) {
if (next.hasChildren()) {
next = next.getFirstChild();
} else {
next = computeFollowing(next);
}
}
return next;
}
private void removeDeadExprStatementSafely(Node n) {
Node parent = n.getParent();
if (n.isEmpty() || (n.isBlock() && !n.hasChildren())) {
// Not always trivial to remove, let FoldConstants work its magic later.
return;
}
// TODO(user): This is a problem with removeNoOpStatements.
// Every expression in a FOR-IN header looks side effect free on its own.
if (NodeUtil.isForIn(parent)) {
return;
}
switch (n.getType()) {
// Removing an unreachable DO node is messy b/c it means we still have
// to execute one iteration. If the DO's body has breaks in the middle,
// it can get even more tricky and code size might actually increase.
case Token.DO:
return;
case Token.BLOCK:
// BLOCKs are used in several ways including wrapping CATCH
// blocks in TRYs
if (parent.isTry() && NodeUtil.isTryCatchNodeContainer(n)) {
return;
}
break;
case Token.CATCH:
Node tryNode = parent.getParent();
NodeUtil.maybeAddFinally(tryNode);
break;
}
if (n.isVar() && !n.getFirstChild().hasChildren()) {
// Very unlikely case, Consider this:
// File 1: {throw 1}
// File 2: {var x}
// The node var x is unreachable in the global scope.
// Before we remove the node, redeclareVarsInsideBranch
// would basically move var x to the beginning of File 2,
// which resulted in zero changes to the AST but triggered
// reportCodeChange().
// Instead, we should just ignore dead variable declarations.
return;
}
removeNode(n);
}
private void removeNode(Node n) {
codeChanged = true;
NodeUtil.redeclareVarsInsideBranch(n);
compiler.reportCodeChange();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Removing " + n.toString());
}
NodeUtil.removeChild(n.getParent(), n);
}
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {}
@Override
public void enterScope(NodeTraversal t) {}
}
|
Fix typo
R=blickly
DELTA=1 (0 added, 0 deleted, 1 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=6203
git-svn-id: 708380be11bb4c96db8d1bd19ea12a301575c487@2491 b0f006be-c8cd-11de-a2e8-8d36a3108c74
| src/com/google/javascript/jscomp/UnreachableCodeElimination.java | <ide><path>rc/com/google/javascript/jscomp/UnreachableCodeElimination.java
<ide> * break. However, if we remove the last break, the 2nd break becomes
<ide> * useless and finally the first break becomes useless as well.
<ide> *
<del> * @return The target of this jump. If the target is also useless jump,
<add> * @returns The target of this jump. If the target is also useless jump,
<ide> * the target of that useless jump recursively.
<ide> */
<ide> @SuppressWarnings("fallthrough") |
||
JavaScript | mit | fdccbbd8d64332af15a7d05bb87ddaaea7fb63a7 | 0 | FLL-SK/teams,FLL-SK/teams | "use strict";
var libCommon = {};
libCommon.noop = function(){}; // to be used for undefined callbacks
libCommon.objPathGet = function(obj, path){
if (typeof path === "string")
return libCommon.objPathGet(obj, path.split('.'));
var ret = obj;
for (var i = 0; i<path.length; i++){
ret = ret[path[i]];
}
return ret;
};
libCommon.getNoCache = function(url){
var d = new Date();
return url+"&ts="+d.toISOString();
};
libCommon.convertLocaleDate2SysDate = function(d,locale){
var a = d.split(/[ :\-\/\.]/g);
var s = "";
switch (locale.substr(3,2)){
case 'US':
s = a[2]+"-"+a[0]+"-"+a[1];
break;
case 'SK':
case 'DE':
case 'GB':
s = a[2]+"-"+a[1]+"-"+a[0];
break;
default:
s = "unknown locale";
}
return s;
};
| public/javascripts/lib/lib_common.js | "use strict";
var libCommon = {};
libCommon.noop = function(){}; // to be used for undefined callbacks
libCommon.objPathGet = function(obj, path){
if (typeof path === "string")
return libCommon.objPathGet(obj, path.split('.'));
var ret = obj;
for (var i = 0; i<path.length; i++){
ret = ret[path[i]];
}
return ret;
};
libCommon.getNoCache = function(url){
var d = new Date();
return url+"&ts="+d.toISOString();
};
};
| date conversion function implemented
| public/javascripts/lib/lib_common.js | date conversion function implemented | <ide><path>ublic/javascripts/lib/lib_common.js
<ide> var d = new Date();
<ide> return url+"&ts="+d.toISOString();
<ide> };
<add>
<add>libCommon.convertLocaleDate2SysDate = function(d,locale){
<add> var a = d.split(/[ :\-\/\.]/g);
<add> var s = "";
<add> switch (locale.substr(3,2)){
<add> case 'US':
<add> s = a[2]+"-"+a[0]+"-"+a[1];
<add> break;
<add> case 'SK':
<add> case 'DE':
<add> case 'GB':
<add> s = a[2]+"-"+a[1]+"-"+a[0];
<add> break;
<add> default:
<add> s = "unknown locale";
<add>
<add> }
<add>
<add> return s;
<add>
<ide> }; |
|
JavaScript | mit | a73ba1c2e222f477eb49f33b80203ea776970584 | 0 | benstoltz/ember.js,michaelBenin/ember.js,practicefusion/ember.js,ryanlabouve/ember.js,nicklv/ember.js,eventualbuddha/ember.js,ming-codes/ember.js,vikram7/ember.js,okuryu/ember.js,zenefits/ember.js,anilmaurya/ember.js,adamesque/ember.js,SaladFork/ember.js,jherdman/ember.js,rwjblue/ember.js,eriktrom/ember.js,chancancode/ember.js,tofanelli/ember.js,wagenet/ember.js,ianstarz/ember.js,rodrigo-morais/ember.js,miguelcobain/ember.js,rlugojr/ember.js,davidpett/ember.js,jasonmit/ember.js,JacobNinja/es6,olivierchatry/ember.js,seanjohnson08/ember.js,xtian/ember.js,mmun/ember.js,latlontude/ember.js,joeruello/ember.js,selvagsz/ember.js,jaswilli/ember.js,davidpett/ember.js,abulrim/ember.js,xtian/ember.js,nvoron23/ember.js,pangratz/ember.js,kmiyashiro/ember.js,kwight/ember.js,JesseQin/ember.js,topaxi/ember.js,adatapost/ember.js,cesarizu/ember.js,martndemus/ember.js,xtian/ember.js,tofanelli/ember.js,GavinJoyce/ember.js,tricknotes/ember.js,ef4/ember.js,kaeufl/ember.js,visualjeff/ember.js,code0100fun/ember.js,sivakumar-kailasam/ember.js,eliotsykes/ember.js,ryrych/ember.js,workmanw/ember.js,fpauser/ember.js,ryanlabouve/ember.js,teddyzeenny/ember.js,GavinJoyce/ember.js,Turbo87/ember.js,delftswa2016/ember.js,xcskier56/ember.js,xcambar/ember.js,jonathanKingston/ember.js,bekzod/ember.js,schreiaj/ember.js,Gaurav0/ember.js,nruth/ember.js,gfvcastro/ember.js,pixelhandler/ember.js,workmanw/ember.js,ming-codes/ember.js,knownasilya/ember.js,fpauser/ember.js,thoov/ember.js,chadhietala/ember.js,8thcolor/ember.js,furkanayhan/ember.js,bantic/ember.js,njagadeesh/ember.js,teddyzeenny/ember.js,rubenrp81/ember.js,jerel/ember.js,ianstarz/ember.js,rondale-sc/ember.js,KevinTCoughlin/ember.js,kellyselden/ember.js,MatrixZ/ember.js,ianstarz/ember.js,gnarf/ember.js,fxkr/ember.js,kiwiupover/ember.js,martndemus/ember.js,csantero/ember.js,omurbilgili/ember.js,slindberg/ember.js,VictorChaun/ember.js,cgvarela/ember.js,zenefits/ember.js,rfsv/ember.js,alexdiliberto/ember.js,xiujunma/ember.js,johanneswuerbach/ember.js,Eric-Guo/ember.js,ridixcr/ember.js,Zagorakiss/ember.js,eliotsykes/ember.js,brzpegasus/ember.js,emberjs/ember.js,faizaanshamsi/ember.js,mtaylor769/ember.js,koriroys/ember.js,asakusuma/ember.js,mike-north/ember.js,machty/ember.js,tsing80/ember.js,tildeio/ember.js,nruth/ember.js,tildeio/ember.js,ridixcr/ember.js,bmac/ember.js,jaswilli/ember.js,nruth/ember.js,selvagsz/ember.js,Zagorakiss/ember.js,jonathanKingston/ember.js,tiegz/ember.js,mallikarjunayaddala/ember.js,intercom/ember.js,twokul/ember.js,kigsmtua/ember.js,delftswa2016/ember.js,joeruello/ember.js,ridixcr/ember.js,lsthornt/ember.js,rot26/ember.js,selvagsz/ember.js,wycats/ember.js,ebryn/ember.js,swarmbox/ember.js,kennethdavidbuck/ember.js,chadhietala/mixonic-ember,duggiefresh/ember.js,williamsbdev/ember.js,elwayman02/ember.js,cesarizu/ember.js,wecc/ember.js,amk221/ember.js,Patsy-issa/ember.js,adamesque/ember.js,howtolearntocode/ember.js,olivierchatry/ember.js,EricSchank/ember.js,kmiyashiro/ember.js,jcope2013/ember.js,johanneswuerbach/ember.js,lazybensch/ember.js,Turbo87/ember.js,marijaselakovic/ember.js,loadimpact/ember.js,paddyobrien/ember.js,sharma1nitish/ember.js,femi-saliu/ember.js,givanse/ember.js,davidpett/ember.js,nathanhammond/ember.js,ThiagoGarciaAlves/ember.js,cowboyd/ember.js,wycats/ember.js,acburdine/ember.js,jplwood/ember.js,jerel/ember.js,Kuzirashi/ember.js,dgeb/ember.js,seanpdoyle/ember.js,furkanayhan/ember.js,lsthornt/ember.js,quaertym/ember.js,jherdman/ember.js,vitch/ember.js,marcioj/ember.js,ubuntuvim/ember.js,sivakumar-kailasam/ember.js,trek/ember.js,ThiagoGarciaAlves/ember.js,cbou/ember.js,howmuchcomputer/ember.js,jplwood/ember.js,HeroicEric/ember.js,kidaa/ember.js,kanongil/ember.js,develoser/ember.js,green-arrow/ember.js,bekzod/ember.js,kwight/ember.js,TriumphantAkash/ember.js,sivakumar-kailasam/ember.js,nightire/ember.js,adatapost/ember.js,knownasilya/ember.js,emberjs/ember.js,claimsmall/ember.js,Krasnyanskiy/ember.js,simudream/ember.js,jish/ember.js,cibernox/ember.js,johnnyshields/ember.js,Serabe/ember.js,bantic/ember.js,marcioj/ember.js,cesarizu/ember.js,chadhietala/ember.js,XrXr/ember.js,getoutreach/ember.js,toddjordan/ember.js,acburdine/ember.js,selvagsz/ember.js,TriumphantAkash/ember.js,balinterdi/ember.js,develoser/ember.js,practicefusion/ember.js,brzpegasus/ember.js,tsing80/ember.js,cowboyd/ember.js,omurbilgili/ember.js,balinterdi/ember.js,csantero/ember.js,koriroys/ember.js,GavinJoyce/ember.js,patricksrobertson/ember.js,jplwood/ember.js,schreiaj/ember.js,Leooo/ember.js,boztek/ember.js,williamsbdev/ember.js,kwight/ember.js,ebryn/ember.js,yonjah/ember.js,xcambar/ember.js,gfvcastro/ember.js,sandstrom/ember.js,xcambar/ember.js,artfuldodger/ember.js,thejameskyle/ember.js,koriroys/ember.js,quaertym/ember.js,xcskier56/ember.js,nickiaconis/ember.js,jmurphyau/ember.js,kidaa/ember.js,furkanayhan/ember.js,yonjah/ember.js,seanjohnson08/ember.js,artfuldodger/ember.js,EricSchank/ember.js,cdl/ember.js,yonjah/ember.js,jayphelps/ember.js,rfsv/ember.js,seanjohnson08/ember.js,marijaselakovic/ember.js,fxkr/ember.js,tomdale/ember.js,vitch/ember.js,kidaa/ember.js,mmpestorich/ember.js,jonathanKingston/ember.js,rodrigo-morais/ember.js,adamesque/ember.js,claimsmall/ember.js,asakusuma/ember.js,Kuzirashi/ember.js,rlugojr/ember.js,krisselden/ember.js,jayphelps/ember.js,sly7-7/ember.js,kanongil/ember.js,yuhualingfeng/ember.js,wycats/ember.js,jaswilli/ember.js,szines/ember.js,cgvarela/ember.js,EricSchank/ember.js,ryanlabouve/ember.js,mixonic/ember.js,mfeckie/ember.js,csantero/ember.js,faizaanshamsi/ember.js,okuryu/ember.js,qaiken/ember.js,Trendy/ember.js,nipunas/ember.js,Turbo87/ember.js,cdl/ember.js,quaertym/ember.js,nickiaconis/ember.js,xcskier56/ember.js,asakusuma/ember.js,fpauser/ember.js,code0100fun/ember.js,wagenet/ember.js,qaiken/ember.js,acburdine/ember.js,bmac/ember.js,fivetanley/ember-tests-izzle,nvoron23/ember.js,givanse/ember.js,latlontude/ember.js,aihua/ember.js,krisselden/ember.js,chadhietala/mixonic-ember,Vassi/ember.js,danielgynn/ember.js,mrjavascript/ember.js,aihua/ember.js,raycohen/ember.js,SaladFork/ember.js,rubenrp81/ember.js,jbrown/ember.js,lazybensch/ember.js,mitchlloyd/ember.js,gdi2290/ember.js,duggiefresh/ember.js,pangratz/ember.js,sharma1nitish/ember.js,jerel/ember.js,yaymukund/ember.js,nathanhammond/ember.js,jasonmit/ember.js,nightire/ember.js,benstoltz/ember.js,nightire/ember.js,HipsterBrown/ember.js,8thcolor/ember.js,Patsy-issa/ember.js,trentmwillis/ember.js,ssured/ember.js,TriumphantAkash/ember.js,szines/ember.js,xcambar/ember.js,marcioj/ember.js,stefanpenner/ember.js,bcardarella/ember.js,martndemus/ember.js,kublaj/ember.js,Vassi/ember.js,anilmaurya/ember.js,Leooo/ember.js,marcioj/ember.js,max-konin/ember.js,Trendy/ember.js,anilmaurya/ember.js,tianxiangbing/ember.js,martndemus/ember.js,cbou/ember.js,NLincoln/ember.js,soulcutter/ember.js,jherdman/ember.js,kublaj/ember.js,wecc/ember.js,opichals/ember.js,swarmbox/ember.js,ubuntuvim/ember.js,visualjeff/ember.js,kigsmtua/ember.js,asakusuma/ember.js,greyhwndz/ember.js,lan0/ember.js,kidaa/ember.js,BrianSipple/ember.js,joeruello/ember.js,JKGisMe/ember.js,garth/ember.js,topaxi/ember.js,dschmidt/ember.js,nickiaconis/ember.js,johnnyshields/ember.js,runspired/ember.js,marijaselakovic/ember.js,faizaanshamsi/ember.js,ming-codes/ember.js,dgeb/ember.js,wagenet/ember.js,max-konin/ember.js,cesarizu/ember.js,seanpdoyle/ember.js,cowboyd/ember.js,XrXr/ember.js,trentmwillis/ember.js,simudream/ember.js,fivetanley/ember-tests-izzle,fxkr/ember.js,tianxiangbing/ember.js,bantic/ember.js,rodrigo-morais/ember.js,jonathanKingston/ember.js,trek/ember.js,udhayam/ember.js,cyjia/ember.js,pixelhandler/ember.js,musically-ut/ember.js,raytiley/ember.js,code0100fun/ember.js,Vassi/ember.js,fivetanley/ember.js,cdl/ember.js,brzpegasus/ember.js,acburdine/ember.js,johanneswuerbach/ember.js,soulcutter/ember.js,qaiken/ember.js,yaymukund/ember.js,lan0/ember.js,opichals/ember.js,blimmer/ember.js,rlugojr/ember.js,eliotsykes/ember.js,alexdiliberto/ember.js,ubuntuvim/ember.js,jaswilli/ember.js,rfsv/ember.js,sivakumar-kailasam/ember.js,jackiewung/ember.js,max-konin/ember.js,antigremlin/ember.js,raytiley/ember.js,thoov/ember.js,max-konin/ember.js,TriumphantAkash/ember.js,raytiley/ember.js,g13013/ember.js,williamsbdev/ember.js,BrianSipple/ember.js,ef4/ember.js,toddjordan/ember.js,rlugojr/ember.js,Serabe/ember.js,raycohen/ember.js,Kuzirashi/ember.js,HeroicEric/ember.js,mitchlloyd/ember.js,cibernox/ember.js,KevinTCoughlin/ember.js,pangratz/ember.js,howmuchcomputer/ember.js,jamesarosen/ember.js,jbrown/ember.js,Gaurav0/ember.js,szines/ember.js,joeruello/ember.js,green-arrow/ember.js,gfvcastro/ember.js,jcope2013/ember.js,nruth/ember.js,benstoltz/ember.js,tricknotes/ember.js,rodrigo-morais/ember.js,tsing80/ember.js,kmiyashiro/ember.js,adatapost/ember.js,JesseQin/ember.js,givanse/ember.js,aihua/ember.js,chadhietala/ember.js,paddyobrien/ember.js,miguelcobain/ember.js,cibernox/ember.js,fxkr/ember.js,BrianSipple/ember.js,cyberkoi/ember.js,seanpdoyle/ember.js,Krasnyanskiy/ember.js,Serabe/ember.js,runspired/ember.js,XrXr/ember.js,tiegz/ember.js,eliotsykes/ember.js,johnnyshields/ember.js,alexspeller/ember.js,mfeckie/ember.js,marijaselakovic/ember.js,miguelcobain/ember.js,kigsmtua/ember.js,develoser/ember.js,nipunas/ember.js,elwayman02/ember.js,elwayman02/ember.js,thoov/ember.js,cbou/ember.js,knownasilya/ember.js,paddyobrien/ember.js,chancancode/ember.js,mmpestorich/ember.js,skeate/ember.js,karthiick/ember.js,mfeckie/ember.js,claimsmall/ember.js,gnarf/ember.js,opichals/ember.js,rubenrp81/ember.js,yaymukund/ember.js,patricksrobertson/ember.js,BrianSipple/ember.js,sandstrom/ember.js,schreiaj/ember.js,tianxiangbing/ember.js,jbrown/ember.js,kaeufl/ember.js,nickiaconis/ember.js,develoser/ember.js,greyhwndz/ember.js,cyberkoi/ember.js,skeate/ember.js,jackiewung/ember.js,kanongil/ember.js,faizaanshamsi/ember.js,yonjah/ember.js,delftswa2016/ember.js,jcope2013/ember.js,twokul/ember.js,rot26/ember.js,csantero/ember.js,Robdel12/ember.js,mitchlloyd/ember.js,johnnyshields/ember.js,amk221/ember.js,mixonic/ember.js,wecc/ember.js,JKGisMe/ember.js,kiwiupover/ember.js,tomdale/ember.js,raytiley/ember.js,yaymukund/ember.js,karthiick/ember.js,mallikarjunayaddala/ember.js,adatapost/ember.js,johanneswuerbach/ember.js,mdehoog/ember.js,Trendy/ember.js,tricknotes/ember.js,jish/ember.js,sly7-7/ember.js,ryanlabouve/ember.js,intercom/ember.js,ebryn/ember.js,tricknotes/ember.js,aihua/ember.js,sharma1nitish/ember.js,fouzelddin/ember.js,fpauser/ember.js,jmurphyau/ember.js,opichals/ember.js,cyjia/ember.js,blimmer/ember.js,eriktrom/ember.js,zenefits/ember.js,xiujunma/ember.js,Patsy-issa/ember.js,sivakumar-kailasam/ember.js,stefanpenner/ember.js,boztek/ember.js,8thcolor/ember.js,visualjeff/ember.js,HipsterBrown/ember.js,artfuldodger/ember.js,claimsmall/ember.js,Gaurav0/ember.js,kaeufl/ember.js,howtolearntocode/ember.js,szines/ember.js,pangratz/ember.js,artfuldodger/ember.js,JacobNinja/es6,howtolearntocode/ember.js,HipsterBrown/ember.js,skeate/ember.js,GavinJoyce/ember.js,simudream/ember.js,machty/ember.js,kaeufl/ember.js,Zagorakiss/ember.js,Robdel12/ember.js,bekzod/ember.js,cgvarela/ember.js,VictorChaun/ember.js,antigremlin/ember.js,fivetanley/ember.js,trek/ember.js,danielgynn/ember.js,ef4/ember.js,trentmwillis/ember.js,kellyselden/ember.js,lazybensch/ember.js,visualjeff/ember.js,NLincoln/ember.js,howtolearntocode/ember.js,jackiewung/ember.js,thoov/ember.js,benstoltz/ember.js,kigsmtua/ember.js,jasonmit/ember.js,tomdale/ember.js,Eric-Guo/ember.js,VictorChaun/ember.js,bekzod/ember.js,fivetanley/ember.js,olivierchatry/ember.js,MatrixZ/ember.js,rwjblue/ember.js,twokul/ember.js,XrXr/ember.js,EricSchank/ember.js,mallikarjunayaddala/ember.js,michaelBenin/ember.js,ridixcr/ember.js,danielgynn/ember.js,mitchlloyd/ember.js,anilmaurya/ember.js,mmpestorich/ember.js,kublaj/ember.js,kwight/ember.js,gnarf/ember.js,mdehoog/ember.js,jplwood/ember.js,swarmbox/ember.js,cyjia/ember.js,duggiefresh/ember.js,rot26/ember.js,gdi2290/ember.js,Trendy/ember.js,ssured/ember.js,kmiyashiro/ember.js,blimmer/ember.js,mrjavascript/ember.js,jayphelps/ember.js,nathanhammond/ember.js,kellyselden/ember.js,jamesarosen/ember.js,seanpdoyle/ember.js,dschmidt/ember.js,jish/ember.js,givanse/ember.js,alexdiliberto/ember.js,abulrim/ember.js,tiegz/ember.js,fouzelddin/ember.js,twokul/ember.js,karthiick/ember.js,kennethdavidbuck/ember.js,tianxiangbing/ember.js,Robdel12/ember.js,pixelhandler/ember.js,bmac/ember.js,Gaurav0/ember.js,mike-north/ember.js,KevinTCoughlin/ember.js,mtaylor769/ember.js,loadimpact/ember.js,howmuchcomputer/ember.js,ubuntuvim/ember.js,seanjohnson08/ember.js,loadimpact/ember.js,SaladFork/ember.js,loadimpact/ember.js,vitch/ember.js,skeate/ember.js,jerel/ember.js,HipsterBrown/ember.js,kanongil/ember.js,udhayam/ember.js,nipunas/ember.js,zenefits/ember.js,cgvarela/ember.js,abulrim/ember.js,swarmbox/ember.js,greyhwndz/ember.js,HeroicEric/ember.js,Leooo/ember.js,gfvcastro/ember.js,runspired/ember.js,wycats/ember.js,lazybensch/ember.js,mallikarjunayaddala/ember.js,elwayman02/ember.js,intercom/ember.js,cyberkoi/ember.js,rot26/ember.js,JacobNinja/es6,alexdiliberto/ember.js,mdehoog/ember.js,thejameskyle/ember.js,Leooo/ember.js,kennethdavidbuck/ember.js,jmurphyau/ember.js,emberjs/ember.js,NLincoln/ember.js,toddjordan/ember.js,MatrixZ/ember.js,musically-ut/ember.js,jamesarosen/ember.js,rfsv/ember.js,g13013/ember.js,williamsbdev/ember.js,jish/ember.js,tsing80/ember.js,thejameskyle/ember.js,Krasnyanskiy/ember.js,brzpegasus/ember.js,raycohen/ember.js,vikram7/ember.js,nicklv/ember.js,chadhietala/ember.js,jasonmit/ember.js,femi-saliu/ember.js,Patsy-issa/ember.js,g13013/ember.js,Turbo87/ember.js,bcardarella/ember.js,mike-north/ember.js,antigremlin/ember.js,omurbilgili/ember.js,njagadeesh/ember.js,cyjia/ember.js,Serabe/ember.js,JKGisMe/ember.js,mdehoog/ember.js,udhayam/ember.js,mfeckie/ember.js,cyberkoi/ember.js,simudream/ember.js,kennethdavidbuck/ember.js,soulcutter/ember.js,ThiagoGarciaAlves/ember.js,Kuzirashi/ember.js,mixonic/ember.js,yuhualingfeng/ember.js,kiwiupover/ember.js,jherdman/ember.js,kublaj/ember.js,lsthornt/ember.js,green-arrow/ember.js,jamesarosen/ember.js,dgeb/ember.js,nathanhammond/ember.js,cjc343/ember.js,patricksrobertson/ember.js,JesseQin/ember.js,practicefusion/ember.js,amk221/ember.js,garth/ember.js,toddjordan/ember.js,intercom/ember.js,omurbilgili/ember.js,Vassi/ember.js,boztek/ember.js,miguelcobain/ember.js,nicklv/ember.js,nicklv/ember.js,vikram7/ember.js,jmurphyau/ember.js,jayphelps/ember.js,rondale-sc/ember.js,slindberg/ember.js,KevinTCoughlin/ember.js,mrjavascript/ember.js,boztek/ember.js,danielgynn/ember.js,trek/ember.js,ef4/ember.js,Zagorakiss/ember.js,karthiick/ember.js,olivierchatry/ember.js,abulrim/ember.js,yuhualingfeng/ember.js,tofanelli/ember.js,Eric-Guo/ember.js,practicefusion/ember.js,code0100fun/ember.js,duggiefresh/ember.js,xiujunma/ember.js,quaertym/ember.js,fouzelddin/ember.js,xcskier56/ember.js,Eric-Guo/ember.js,tiegz/ember.js,mmun/ember.js,MatrixZ/ember.js,blimmer/ember.js,ThiagoGarciaAlves/ember.js,nipunas/ember.js,balinterdi/ember.js,cjc343/ember.js,sandstrom/ember.js,Robdel12/ember.js,cjc343/ember.js,rwjblue/ember.js,okuryu/ember.js,bantic/ember.js,8thcolor/ember.js,nvoron23/ember.js,stefanpenner/ember.js,latlontude/ember.js,gdi2290/ember.js,xiujunma/ember.js,cjc343/ember.js,rwjblue/ember.js,fouzelddin/ember.js,patricksrobertson/ember.js,jcope2013/ember.js,jasonmit/ember.js,cdl/ember.js,runspired/ember.js,furkanayhan/ember.js,topaxi/ember.js,delftswa2016/ember.js,kellyselden/ember.js,femi-saliu/ember.js,mrjavascript/ember.js,davidpett/ember.js,nightire/ember.js,yuhualingfeng/ember.js,njagadeesh/ember.js,soulcutter/ember.js,cowboyd/ember.js,jackiewung/ember.js,udhayam/ember.js,rubenrp81/ember.js,pixelhandler/ember.js,femi-saliu/ember.js,xtian/ember.js,cibernox/ember.js,rondale-sc/ember.js,topaxi/ember.js,sharma1nitish/ember.js,bcardarella/ember.js,JesseQin/ember.js,lan0/ember.js,JKGisMe/ember.js,vikram7/ember.js,trentmwillis/ember.js,njagadeesh/ember.js,getoutreach/ember.js,HeroicEric/ember.js,schreiaj/ember.js,qaiken/ember.js,lsthornt/ember.js,sly7-7/ember.js,Krasnyanskiy/ember.js,howmuchcomputer/ember.js,amk221/ember.js,bmac/ember.js,cbou/ember.js,eventualbuddha/ember.js,alexspeller/ember.js,VictorChaun/ember.js,green-arrow/ember.js,mike-north/ember.js,nvoron23/ember.js,workmanw/ember.js,dgeb/ember.js,ryrych/ember.js,lan0/ember.js,slindberg/ember.js,tofanelli/ember.js,chadhietala/mixonic-ember,NLincoln/ember.js,koriroys/ember.js,antigremlin/ember.js,greyhwndz/ember.js,workmanw/ember.js,dschmidt/ember.js,thejameskyle/ember.js,tildeio/ember.js,wecc/ember.js,SaladFork/ember.js,ianstarz/ember.js | // ==========================================================================
// Project: Ember Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('ember-metal/core');
require('ember-metal/accessors');
require('ember-metal/computed');
require('ember-metal/properties');
require('ember-metal/observer');
require('ember-metal/utils');
require('ember-metal/array');
require('ember-metal/binding');
var Mixin, MixinDelegate, REQUIRED, Alias;
var classToString, superClassString;
var a_map = Ember.ArrayUtils.map;
var a_indexOf = Ember.ArrayUtils.indexOf;
var a_forEach = Ember.ArrayUtils.forEach;
var a_slice = Array.prototype.slice;
var EMPTY_META = {}; // dummy for non-writable meta
var META_SKIP = { __emberproto__: true, __ember_count__: true };
var o_create = Ember.platform.create;
/** @private */
function meta(obj, writable) {
var m = Ember.meta(obj, writable!==false), ret = m.mixins;
if (writable===false) return ret || EMPTY_META;
if (!ret) {
ret = m.mixins = { __emberproto__: obj };
} else if (ret.__emberproto__ !== obj) {
ret = m.mixins = o_create(ret);
ret.__emberproto__ = obj;
}
return ret;
}
/** @private */
function initMixin(mixin, args) {
if (args && args.length > 0) {
mixin.mixins = a_map(args, function(x) {
if (x instanceof Mixin) return x;
// Note: Manually setup a primitive mixin here. This is the only
// way to actually get a primitive mixin. This way normal creation
// of mixins will give you combined mixins...
var mixin = new Mixin();
mixin.properties = x;
return mixin;
});
}
return mixin;
}
var NATIVES = [Boolean, Object, Number, Array, Date, String];
/** @private */
function isMethod(obj) {
if ('function' !== typeof obj || obj.isMethod===false) return false;
return a_indexOf(NATIVES, obj)<0;
}
/** @private */
function mergeMixins(mixins, m, descs, values, base) {
var len = mixins.length, idx, mixin, guid, props, value, key, ovalue, concats;
/** @private */
function removeKeys(keyName) {
delete descs[keyName];
delete values[keyName];
}
for(idx=0;idx<len;idx++) {
mixin = mixins[idx];
if (!mixin) throw new Error('Null value found in Ember.mixin()');
if (mixin instanceof Mixin) {
guid = Ember.guidFor(mixin);
if (m[guid]) continue;
m[guid] = mixin;
props = mixin.properties;
} else {
props = mixin; // apply anonymous mixin properties
}
if (props) {
// reset before adding each new mixin to pickup concats from previous
concats = values.concatenatedProperties || base.concatenatedProperties;
if (props.concatenatedProperties) {
concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties;
}
for (key in props) {
if (!props.hasOwnProperty(key)) continue;
value = props[key];
if (value instanceof Ember.Descriptor) {
if (value === REQUIRED && descs[key]) { continue; }
descs[key] = value;
values[key] = undefined;
} else {
// impl super if needed...
if (isMethod(value)) {
ovalue = (descs[key] === Ember.SIMPLE_PROPERTY) && values[key];
if (!ovalue) ovalue = base[key];
if ('function' !== typeof ovalue) ovalue = null;
if (ovalue) {
var o = value.__ember_observes__, ob = value.__ember_observesBefore__;
value = Ember.wrap(value, ovalue);
value.__ember_observes__ = o;
value.__ember_observesBefore__ = ob;
}
} else if ((concats && a_indexOf(concats, key)>=0) || key === 'concatenatedProperties') {
var baseValue = values[key] || base[key];
value = baseValue ? baseValue.concat(value) : Ember.makeArray(value);
}
descs[key] = Ember.SIMPLE_PROPERTY;
values[key] = value;
}
}
// manually copy toString() because some JS engines do not enumerate it
if (props.hasOwnProperty('toString')) {
base.toString = props.toString;
}
} else if (mixin.mixins) {
mergeMixins(mixin.mixins, m, descs, values, base);
if (mixin._without) a_forEach(mixin._without, removeKeys);
}
}
}
/** @private */
var defineProperty = Ember.defineProperty;
/** @private */
function writableReq(obj) {
var m = Ember.meta(obj), req = m.required;
if (!req || (req.__emberproto__ !== obj)) {
req = m.required = req ? o_create(req) : { __ember_count__: 0 };
req.__emberproto__ = obj;
}
return req;
}
/** @private */
function getObserverPaths(value) {
return ('function' === typeof value) && value.__ember_observes__;
}
/** @private */
function getBeforeObserverPaths(value) {
return ('function' === typeof value) && value.__ember_observesBefore__;
}
var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/;
function detectBinding(obj, key, m) {
if (IS_BINDING.test(key)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = { __emberproto__: obj };
} else if (bindings.__emberproto__ !== obj) {
bindings = m.bindings = o_create(m.bindings);
bindings.__emberproto__ = obj;
}
bindings[key] = true;
}
}
function connectBindings(obj, m) {
if (m === undefined) {
m = Ember.meta(obj);
}
var bindings = m.bindings, key, binding;
if (bindings) {
for (key in bindings) {
binding = key !== '__emberproto__' && obj[key];
if (binding) {
if (binding instanceof Ember.Binding) {
binding = binding.copy(); // copy prototypes' instance
binding.to(key.slice(0, -7));
} else {
binding = new Ember.Binding(key.slice(0,-7), binding);
}
binding.connect(obj);
obj[key] = binding;
}
}
}
}
/** @private */
function applyMixin(obj, mixins, partial) {
var descs = {}, values = {}, m = Ember.meta(obj), req = m.required;
var key, willApply, didApply, value, desc;
// Go through all mixins and hashes passed in, and:
//
// * Handle concatenated properties
// * Set up _super wrapping if necessary
// * Set up descriptors (simple, watched or computed properties)
// * Copying `toString` in broken browsers
mergeMixins(mixins, meta(obj), descs, values, obj);
if (MixinDelegate.detect(obj)) {
willApply = values.willApplyProperty || obj.willApplyProperty;
didApply = values.didApplyProperty || obj.didApplyProperty;
}
for(key in descs) {
if (!descs.hasOwnProperty(key)) continue;
desc = descs[key];
value = values[key];
if (desc === REQUIRED) {
if (!(key in obj)) {
if (!partial) throw new Error('Required property not defined: '+key);
// for partial applies add to hash of required keys
req = writableReq(obj);
req.__ember_count__++;
req[key] = true;
}
} else {
while (desc instanceof Alias) {
var altKey = desc.methodName;
if (descs[altKey]) {
value = values[altKey];
desc = descs[altKey];
} else if (m.descs[altKey]) {
desc = m.descs[altKey];
value = desc.val(obj, altKey);
} else {
value = obj[altKey];
desc = Ember.SIMPLE_PROPERTY;
}
}
if (willApply) willApply.call(obj, key);
var observerPaths = getObserverPaths(value),
curObserverPaths = observerPaths && getObserverPaths(obj[key]),
beforeObserverPaths = getBeforeObserverPaths(value),
curBeforeObserverPaths = beforeObserverPaths && getBeforeObserverPaths(obj[key]),
len, idx;
if (curObserverPaths) {
len = curObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.removeObserver(obj, curObserverPaths[idx], null, key);
}
}
if (curBeforeObserverPaths) {
len = curBeforeObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.removeBeforeObserver(obj, curBeforeObserverPaths[idx], null,key);
}
}
detectBinding(obj, key, m);
defineProperty(obj, key, desc, value);
if (observerPaths) {
len = observerPaths.length;
for(idx=0;idx<len;idx++) {
Ember.addObserver(obj, observerPaths[idx], null, key);
}
}
if (beforeObserverPaths) {
len = beforeObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.addBeforeObserver(obj, beforeObserverPaths[idx], null, key);
}
}
if (req && req[key]) {
req = writableReq(obj);
req.__ember_count__--;
req[key] = false;
}
if (didApply) didApply.call(obj, key);
}
}
if (!partial) { // don't apply to prototype
value = connectBindings(obj, m);
}
// Make sure no required attrs remain
if (!partial && req && req.__ember_count__>0) {
var keys = [];
for(key in req) {
if (META_SKIP[key]) continue;
keys.push(key);
}
throw new Error('Required properties not defined: '+keys.join(','));
}
return obj;
}
Ember.mixin = function(obj) {
var args = a_slice.call(arguments, 1);
return applyMixin(obj, args, false);
};
/**
@class
The `Ember.Mixin` class allows you to create mixins, whose properties can be
added to other classes. For instance,
App.Editable = Ember.Mixin.create({
edit: function() {
console.log('starting to edit');
this.set('isEditing', true);
},
isEditing: false
});
// Mix mixins into classes by passing them as the first arguments to
// .extend or .create.
App.CommentView = Ember.View.extend(App.Editable, {
template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}')
});
commentView = App.CommentView.create();
commentView.edit(); // => outputs 'starting to edit'
Note that Mixins are created with `Ember.Mixin.create`, not
`Ember.Mixin.extend`.
*/
Ember.Mixin = function() { return initMixin(this, arguments); };
/** @private */
Mixin = Ember.Mixin;
/** @private */
Mixin._apply = applyMixin;
Mixin.applyPartial = function(obj) {
var args = a_slice.call(arguments, 1);
return applyMixin(obj, args, true);
};
Mixin.finishPartial = function(obj) {
connectBindings(obj);
return obj;
};
Mixin.create = function() {
classToString.processed = false;
var M = this;
return initMixin(new M(), arguments);
};
Mixin.prototype.reopen = function() {
var mixin, tmp;
if (this.properties) {
mixin = Mixin.create();
mixin.properties = this.properties;
delete this.properties;
this.mixins = [mixin];
}
var len = arguments.length, mixins = this.mixins, idx;
for(idx=0;idx<len;idx++) {
mixin = arguments[idx];
if (mixin instanceof Mixin) {
mixins.push(mixin);
} else {
tmp = Mixin.create();
tmp.properties = mixin;
mixins.push(tmp);
}
}
return this;
};
var TMP_ARRAY = [];
Mixin.prototype.apply = function(obj) {
TMP_ARRAY[0] = this;
var ret = applyMixin(obj, TMP_ARRAY, false);
TMP_ARRAY.length=0;
return ret;
};
Mixin.prototype.applyPartial = function(obj) {
TMP_ARRAY[0] = this;
var ret = applyMixin(obj, TMP_ARRAY, true);
TMP_ARRAY.length=0;
return ret;
};
/** @private */
function _detect(curMixin, targetMixin, seen) {
var guid = Ember.guidFor(curMixin);
if (seen[guid]) return false;
seen[guid] = true;
if (curMixin === targetMixin) return true;
var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0;
while(--loc >= 0) {
if (_detect(mixins[loc], targetMixin, seen)) return true;
}
return false;
}
Mixin.prototype.detect = function(obj) {
if (!obj) return false;
if (obj instanceof Mixin) return _detect(obj, this, {});
return !!meta(obj, false)[Ember.guidFor(this)];
};
Mixin.prototype.without = function() {
var ret = new Mixin(this);
ret._without = a_slice.call(arguments);
return ret;
};
/** @private */
function _keys(ret, mixin, seen) {
if (seen[Ember.guidFor(mixin)]) return;
seen[Ember.guidFor(mixin)] = true;
if (mixin.properties) {
var props = mixin.properties;
for(var key in props) {
if (props.hasOwnProperty(key)) ret[key] = true;
}
} else if (mixin.mixins) {
a_forEach(mixin.mixins, function(x) { _keys(ret, x, seen); });
}
}
Mixin.prototype.keys = function() {
var keys = {}, seen = {}, ret = [];
_keys(keys, this, seen);
for(var key in keys) {
if (keys.hasOwnProperty(key)) ret.push(key);
}
return ret;
};
/** @private - make Mixin's have nice displayNames */
var NAME_KEY = Ember.GUID_KEY+'_name';
var get = Ember.get;
/** @private */
function processNames(paths, root, seen) {
var idx = paths.length;
for(var key in root) {
if (!root.hasOwnProperty || !root.hasOwnProperty(key)) continue;
var obj = root[key];
paths[idx] = key;
if (obj && obj.toString === classToString) {
obj[NAME_KEY] = paths.join('.');
} else if (obj && get(obj, 'isNamespace')) {
if (seen[Ember.guidFor(obj)]) continue;
seen[Ember.guidFor(obj)] = true;
processNames(paths, obj, seen);
}
}
paths.length = idx; // cut out last item
}
/** @private */
function findNamespaces() {
var Namespace = Ember.Namespace, obj, isNamespace;
if (Namespace.PROCESSED) { return; }
for (var prop in window) {
// get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox.
// globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage
if (prop === "globalStorage" && window.StorageList && window.globalStorage instanceof window.StorageList) { continue; }
// Unfortunately, some versions of IE don't support window.hasOwnProperty
if (window.hasOwnProperty && !window.hasOwnProperty(prop)) { continue; }
// At times we are not allowed to access certain properties for security reasons.
// There are also times where even if we can access them, we are not allowed to access their properties.
try {
obj = window[prop];
isNamespace = obj && get(obj, 'isNamespace');
} catch (e) {
continue;
}
if (isNamespace) {
Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop));
obj[NAME_KEY] = prop;
}
}
}
Ember.identifyNamespaces = findNamespaces;
/** @private */
superClassString = function(mixin) {
var superclass = mixin.superclass;
if (superclass) {
if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; }
else { return superClassString(superclass); }
} else {
return;
}
};
/** @private */
classToString = function() {
var Namespace = Ember.Namespace, namespace;
// TODO: Namespace should really be in Metal
if (Namespace) {
if (!this[NAME_KEY] && !classToString.processed) {
if (!Namespace.PROCESSED) {
findNamespaces();
Namespace.PROCESSED = true;
}
classToString.processed = true;
var namespaces = Namespace.NAMESPACES;
for (var i=0, l=namespaces.length; i<l; i++) {
namespace = namespaces[i];
processNames([namespace.toString()], namespace, {});
}
}
}
if (this[NAME_KEY]) {
return this[NAME_KEY];
} else {
var str = superClassString(this);
if (str) {
return "(subclass of " + str + ")";
} else {
return "(unknown mixin)";
}
}
};
Mixin.prototype.toString = classToString;
// returns the mixins currently applied to the specified object
// TODO: Make Ember.mixin
Mixin.mixins = function(obj) {
var ret = [], mixins = meta(obj, false), key, mixin;
for(key in mixins) {
if (META_SKIP[key]) continue;
mixin = mixins[key];
// skip primitive mixins since these are always anonymous
if (!mixin.properties) ret.push(mixins[key]);
}
return ret;
};
REQUIRED = new Ember.Descriptor();
REQUIRED.toString = function() { return '(Required Property)'; };
Ember.required = function() {
return REQUIRED;
};
/** @private */
Alias = function(methodName) {
this.methodName = methodName;
};
Alias.prototype = new Ember.Descriptor();
Ember.alias = function(methodName) {
return new Alias(methodName);
};
Ember.MixinDelegate = Mixin.create({
willApplyProperty: Ember.required(),
didApplyProperty: Ember.required()
});
/** @private */
MixinDelegate = Ember.MixinDelegate;
// ..........................................................
// OBSERVER HELPER
//
Ember.observer = function(func) {
var paths = a_slice.call(arguments, 1);
func.__ember_observes__ = paths;
return func;
};
Ember.beforeObserver = function(func) {
var paths = a_slice.call(arguments, 1);
func.__ember_observesBefore__ = paths;
return func;
};
| packages/ember-metal/lib/mixin.js | // ==========================================================================
// Project: Ember Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('ember-metal/core');
require('ember-metal/accessors');
require('ember-metal/computed');
require('ember-metal/properties');
require('ember-metal/observer');
require('ember-metal/utils');
require('ember-metal/array');
require('ember-metal/binding');
var Mixin, MixinDelegate, REQUIRED, Alias;
var classToString, superClassString;
var a_map = Ember.ArrayUtils.map;
var a_indexOf = Ember.ArrayUtils.indexOf;
var a_forEach = Ember.ArrayUtils.forEach;
var a_slice = Array.prototype.slice;
var EMPTY_META = {}; // dummy for non-writable meta
var META_SKIP = { __emberproto__: true, __ember_count__: true };
var o_create = Ember.platform.create;
/** @private */
function meta(obj, writable) {
var m = Ember.meta(obj, writable!==false), ret = m.mixins;
if (writable===false) return ret || EMPTY_META;
if (!ret) {
ret = m.mixins = { __emberproto__: obj };
} else if (ret.__emberproto__ !== obj) {
ret = m.mixins = o_create(ret);
ret.__emberproto__ = obj;
}
return ret;
}
/** @private */
function initMixin(mixin, args) {
if (args && args.length > 0) {
mixin.mixins = a_map(args, function(x) {
if (x instanceof Mixin) return x;
// Note: Manually setup a primitive mixin here. This is the only
// way to actually get a primitive mixin. This way normal creation
// of mixins will give you combined mixins...
var mixin = new Mixin();
mixin.properties = x;
return mixin;
});
}
return mixin;
}
var NATIVES = [Boolean, Object, Number, Array, Date, String];
/** @private */
function isMethod(obj) {
if ('function' !== typeof obj || obj.isMethod===false) return false;
return a_indexOf(NATIVES, obj)<0;
}
/** @private */
function mergeMixins(mixins, m, descs, values, base) {
var len = mixins.length, idx, mixin, guid, props, value, key, ovalue, concats;
/** @private */
function removeKeys(keyName) {
delete descs[keyName];
delete values[keyName];
}
for(idx=0;idx<len;idx++) {
mixin = mixins[idx];
if (!mixin) throw new Error('Null value found in Ember.mixin()');
if (mixin instanceof Mixin) {
guid = Ember.guidFor(mixin);
if (m[guid]) continue;
m[guid] = mixin;
props = mixin.properties;
} else {
props = mixin; // apply anonymous mixin properties
}
if (props) {
// reset before adding each new mixin to pickup concats from previous
concats = values.concatenatedProperties || base.concatenatedProperties;
if (props.concatenatedProperties) {
concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties;
}
for (key in props) {
if (!props.hasOwnProperty(key)) continue;
value = props[key];
if (value instanceof Ember.Descriptor) {
if (value === REQUIRED && descs[key]) { continue; }
descs[key] = value;
values[key] = undefined;
} else {
// impl super if needed...
if (isMethod(value)) {
ovalue = (descs[key] === Ember.SIMPLE_PROPERTY) && values[key];
if (!ovalue) ovalue = base[key];
if ('function' !== typeof ovalue) ovalue = null;
if (ovalue) {
var o = value.__ember_observes__, ob = value.__ember_observesBefore__;
value = Ember.wrap(value, ovalue);
value.__ember_observes__ = o;
value.__ember_observesBefore__ = ob;
}
} else if ((concats && a_indexOf(concats, key)>=0) || key === 'concatenatedProperties') {
var baseValue = values[key] || base[key];
value = baseValue ? baseValue.concat(value) : Ember.makeArray(value);
}
descs[key] = Ember.SIMPLE_PROPERTY;
values[key] = value;
}
}
// manually copy toString() because some JS engines do not enumerate it
if (props.hasOwnProperty('toString')) {
base.toString = props.toString;
}
} else if (mixin.mixins) {
mergeMixins(mixin.mixins, m, descs, values, base);
if (mixin._without) a_forEach(mixin._without, removeKeys);
}
}
}
/** @private */
var defineProperty = Ember.defineProperty;
/** @private */
function writableReq(obj) {
var m = Ember.meta(obj), req = m.required;
if (!req || (req.__emberproto__ !== obj)) {
req = m.required = req ? o_create(req) : { __ember_count__: 0 };
req.__emberproto__ = obj;
}
return req;
}
/** @private */
function getObserverPaths(value) {
return ('function' === typeof value) && value.__ember_observes__;
}
/** @private */
function getBeforeObserverPaths(value) {
return ('function' === typeof value) && value.__ember_observesBefore__;
}
var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/;
function detectBinding(obj, key, m) {
if (IS_BINDING.test(key)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = { __emberproto__: obj };
} else if (bindings.__emberproto__ !== obj) {
bindings = m.bindings = o_create(m.bindings);
bindings.__emberproto__ = obj;
}
bindings[key] = true;
}
}
function connectBindings(obj, m) {
if (m === undefined) {
m = Ember.meta(obj);
}
var bindings = m.bindings, key, binding;
if (bindings) {
for (key in bindings) {
binding = key !== '__emberproto__' && obj[key];
if (binding) {
if (binding instanceof Ember.Binding) {
binding = binding.copy(); // copy prototypes' instance
binding.to(key.slice(0, -7));
} else {
binding = new Ember.Binding(key.slice(0,-7), binding);
}
binding.connect(obj);
obj[key] = binding;
}
}
}
}
/** @private */
function applyMixin(obj, mixins, partial) {
var descs = {}, values = {}, m = Ember.meta(obj), req = m.required;
var key, willApply, didApply, value, desc;
// Go through all mixins and hashes passed in, and:
//
// * Handle concatenated properties
// * Set up _super wrapping if necessary
// * Set up descriptors (simple, watched or computed properties)
// * Copying `toString` in broken browsers
mergeMixins(mixins, meta(obj), descs, values, obj);
if (MixinDelegate.detect(obj)) {
willApply = values.willApplyProperty || obj.willApplyProperty;
didApply = values.didApplyProperty || obj.didApplyProperty;
}
for(key in descs) {
if (!descs.hasOwnProperty(key)) continue;
desc = descs[key];
value = values[key];
if (desc === REQUIRED) {
if (!(key in obj)) {
if (!partial) throw new Error('Required property not defined: '+key);
// for partial applies add to hash of required keys
req = writableReq(obj);
req.__ember_count__++;
req[key] = true;
}
} else {
while (desc instanceof Alias) {
var altKey = desc.methodName;
if (descs[altKey]) {
value = values[altKey];
desc = descs[altKey];
} else if (m.descs[altKey]) {
desc = m.descs[altKey];
value = desc.val(obj, altKey);
} else {
value = obj[altKey];
desc = Ember.SIMPLE_PROPERTY;
}
}
if (willApply) willApply.call(obj, key);
var observerPaths = getObserverPaths(value),
curObserverPaths = observerPaths && getObserverPaths(obj[key]),
beforeObserverPaths = getBeforeObserverPaths(value),
curBeforeObserverPaths = beforeObserverPaths && getBeforeObserverPaths(obj[key]),
len, idx;
if (curObserverPaths) {
len = curObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.removeObserver(obj, curObserverPaths[idx], null, key);
}
}
if (curBeforeObserverPaths) {
len = curBeforeObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.removeBeforeObserver(obj, curBeforeObserverPaths[idx], null,key);
}
}
detectBinding(obj, key, m);
defineProperty(obj, key, desc, value);
if (observerPaths) {
len = observerPaths.length;
for(idx=0;idx<len;idx++) {
Ember.addObserver(obj, observerPaths[idx], null, key);
}
}
if (beforeObserverPaths) {
len = beforeObserverPaths.length;
for(idx=0;idx<len;idx++) {
Ember.addBeforeObserver(obj, beforeObserverPaths[idx], null, key);
}
}
if (req && req[key]) {
req = writableReq(obj);
req.__ember_count__--;
req[key] = false;
}
if (didApply) didApply.call(obj, key);
}
}
if (!partial) { // don't apply to prototype
value = connectBindings(obj, m);
}
// Make sure no required attrs remain
if (!partial && req && req.__ember_count__>0) {
var keys = [];
for(key in req) {
if (META_SKIP[key]) continue;
keys.push(key);
}
throw new Error('Required properties not defined: '+keys.join(','));
}
return obj;
}
Ember.mixin = function(obj) {
var args = a_slice.call(arguments, 1);
return applyMixin(obj, args, false);
};
/**
@constructor
*/
Ember.Mixin = function() { return initMixin(this, arguments); };
/** @private */
Mixin = Ember.Mixin;
/** @private */
Mixin._apply = applyMixin;
Mixin.applyPartial = function(obj) {
var args = a_slice.call(arguments, 1);
return applyMixin(obj, args, true);
};
Mixin.finishPartial = function(obj) {
connectBindings(obj);
return obj;
};
Mixin.create = function() {
classToString.processed = false;
var M = this;
return initMixin(new M(), arguments);
};
Mixin.prototype.reopen = function() {
var mixin, tmp;
if (this.properties) {
mixin = Mixin.create();
mixin.properties = this.properties;
delete this.properties;
this.mixins = [mixin];
}
var len = arguments.length, mixins = this.mixins, idx;
for(idx=0;idx<len;idx++) {
mixin = arguments[idx];
if (mixin instanceof Mixin) {
mixins.push(mixin);
} else {
tmp = Mixin.create();
tmp.properties = mixin;
mixins.push(tmp);
}
}
return this;
};
var TMP_ARRAY = [];
Mixin.prototype.apply = function(obj) {
TMP_ARRAY[0] = this;
var ret = applyMixin(obj, TMP_ARRAY, false);
TMP_ARRAY.length=0;
return ret;
};
Mixin.prototype.applyPartial = function(obj) {
TMP_ARRAY[0] = this;
var ret = applyMixin(obj, TMP_ARRAY, true);
TMP_ARRAY.length=0;
return ret;
};
/** @private */
function _detect(curMixin, targetMixin, seen) {
var guid = Ember.guidFor(curMixin);
if (seen[guid]) return false;
seen[guid] = true;
if (curMixin === targetMixin) return true;
var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0;
while(--loc >= 0) {
if (_detect(mixins[loc], targetMixin, seen)) return true;
}
return false;
}
Mixin.prototype.detect = function(obj) {
if (!obj) return false;
if (obj instanceof Mixin) return _detect(obj, this, {});
return !!meta(obj, false)[Ember.guidFor(this)];
};
Mixin.prototype.without = function() {
var ret = new Mixin(this);
ret._without = a_slice.call(arguments);
return ret;
};
/** @private */
function _keys(ret, mixin, seen) {
if (seen[Ember.guidFor(mixin)]) return;
seen[Ember.guidFor(mixin)] = true;
if (mixin.properties) {
var props = mixin.properties;
for(var key in props) {
if (props.hasOwnProperty(key)) ret[key] = true;
}
} else if (mixin.mixins) {
a_forEach(mixin.mixins, function(x) { _keys(ret, x, seen); });
}
}
Mixin.prototype.keys = function() {
var keys = {}, seen = {}, ret = [];
_keys(keys, this, seen);
for(var key in keys) {
if (keys.hasOwnProperty(key)) ret.push(key);
}
return ret;
};
/** @private - make Mixin's have nice displayNames */
var NAME_KEY = Ember.GUID_KEY+'_name';
var get = Ember.get;
/** @private */
function processNames(paths, root, seen) {
var idx = paths.length;
for(var key in root) {
if (!root.hasOwnProperty || !root.hasOwnProperty(key)) continue;
var obj = root[key];
paths[idx] = key;
if (obj && obj.toString === classToString) {
obj[NAME_KEY] = paths.join('.');
} else if (obj && get(obj, 'isNamespace')) {
if (seen[Ember.guidFor(obj)]) continue;
seen[Ember.guidFor(obj)] = true;
processNames(paths, obj, seen);
}
}
paths.length = idx; // cut out last item
}
/** @private */
function findNamespaces() {
var Namespace = Ember.Namespace, obj, isNamespace;
if (Namespace.PROCESSED) { return; }
for (var prop in window) {
// get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox.
// globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage
if (prop === "globalStorage" && window.StorageList && window.globalStorage instanceof window.StorageList) { continue; }
// Unfortunately, some versions of IE don't support window.hasOwnProperty
if (window.hasOwnProperty && !window.hasOwnProperty(prop)) { continue; }
// At times we are not allowed to access certain properties for security reasons.
// There are also times where even if we can access them, we are not allowed to access their properties.
try {
obj = window[prop];
isNamespace = obj && get(obj, 'isNamespace');
} catch (e) {
continue;
}
if (isNamespace) {
Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop));
obj[NAME_KEY] = prop;
}
}
}
Ember.identifyNamespaces = findNamespaces;
/** @private */
superClassString = function(mixin) {
var superclass = mixin.superclass;
if (superclass) {
if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; }
else { return superClassString(superclass); }
} else {
return;
}
};
/** @private */
classToString = function() {
var Namespace = Ember.Namespace, namespace;
// TODO: Namespace should really be in Metal
if (Namespace) {
if (!this[NAME_KEY] && !classToString.processed) {
if (!Namespace.PROCESSED) {
findNamespaces();
Namespace.PROCESSED = true;
}
classToString.processed = true;
var namespaces = Namespace.NAMESPACES;
for (var i=0, l=namespaces.length; i<l; i++) {
namespace = namespaces[i];
processNames([namespace.toString()], namespace, {});
}
}
}
if (this[NAME_KEY]) {
return this[NAME_KEY];
} else {
var str = superClassString(this);
if (str) {
return "(subclass of " + str + ")";
} else {
return "(unknown mixin)";
}
}
};
Mixin.prototype.toString = classToString;
// returns the mixins currently applied to the specified object
// TODO: Make Ember.mixin
Mixin.mixins = function(obj) {
var ret = [], mixins = meta(obj, false), key, mixin;
for(key in mixins) {
if (META_SKIP[key]) continue;
mixin = mixins[key];
// skip primitive mixins since these are always anonymous
if (!mixin.properties) ret.push(mixins[key]);
}
return ret;
};
REQUIRED = new Ember.Descriptor();
REQUIRED.toString = function() { return '(Required Property)'; };
Ember.required = function() {
return REQUIRED;
};
/** @private */
Alias = function(methodName) {
this.methodName = methodName;
};
Alias.prototype = new Ember.Descriptor();
Ember.alias = function(methodName) {
return new Alias(methodName);
};
Ember.MixinDelegate = Mixin.create({
willApplyProperty: Ember.required(),
didApplyProperty: Ember.required()
});
/** @private */
MixinDelegate = Ember.MixinDelegate;
// ..........................................................
// OBSERVER HELPER
//
Ember.observer = function(func) {
var paths = a_slice.call(arguments, 1);
func.__ember_observes__ = paths;
return func;
};
Ember.beforeObserver = function(func) {
var paths = a_slice.call(arguments, 1);
func.__ember_observesBefore__ = paths;
return func;
};
| Add documentation for Ember.Mixin
| packages/ember-metal/lib/mixin.js | Add documentation for Ember.Mixin | <ide><path>ackages/ember-metal/lib/mixin.js
<ide>
<ide>
<ide> /**
<del> @constructor
<add> @class
<add>
<add> The `Ember.Mixin` class allows you to create mixins, whose properties can be
<add> added to other classes. For instance,
<add>
<add> App.Editable = Ember.Mixin.create({
<add> edit: function() {
<add> console.log('starting to edit');
<add> this.set('isEditing', true);
<add> },
<add> isEditing: false
<add> });
<add>
<add> // Mix mixins into classes by passing them as the first arguments to
<add> // .extend or .create.
<add> App.CommentView = Ember.View.extend(App.Editable, {
<add> template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}')
<add> });
<add>
<add> commentView = App.CommentView.create();
<add> commentView.edit(); // => outputs 'starting to edit'
<add>
<add> Note that Mixins are created with `Ember.Mixin.create`, not
<add> `Ember.Mixin.extend`.
<ide> */
<ide> Ember.Mixin = function() { return initMixin(this, arguments); };
<ide> |
|
Java | lgpl-2.1 | 244cf207e5925eacd48cac8252e82832fc97d72c | 0 | ggiudetti/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.xml.containerpage;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.containerpage.shared.CmsContainerElement;
import org.opencms.ade.containerpage.shared.CmsContainerElement.ModelGroupState;
import org.opencms.ade.containerpage.shared.CmsInheritanceInfo;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsUUID;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentPropertyHelper;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* One element of a container in a container page.<p>
*
* @since 8.0
*/
public class CmsContainerElementBean implements Cloneable {
/** Flag indicating if a new element should be created replacing the given one on first edit of a container-page. */
private final boolean m_createNew;
/** The client ADE editor hash. */
private transient String m_editorHash;
/** The element's structure id. */
private CmsUUID m_elementId;
/** The formatter's structure id. */
private CmsUUID m_formatterId;
/** The configured properties. */
private Map<String, String> m_individualSettings;
/** The inheritance info of this element. */
private CmsInheritanceInfo m_inheritanceInfo;
/** Indicates whether the represented resource is in memory only and not in the VFS. */
private boolean m_inMemoryOnly;
/** Indicating if the element resource is released and not expired. */
private boolean m_releasedAndNotExpired;
/** The resource of this element. */
private transient CmsResource m_resource;
/** The settings of this element containing also default values. */
private transient Map<String, String> m_settings;
/** The element site path, only set while rendering. */
private String m_sitePath;
/** Indicates the element bean has a temporary file content set. */
private boolean m_temporaryContent;
/**
* Creates a new container page element bean.<p>
*
* @param elementId the element's structure id
* @param formatterId the formatter's structure id, could be <code>null</code>
* @param individualSettings the element settings as a map of name/value pairs
* @param createNew <code>true</code> if a new element should be created replacing the given one on first edit of a container-page
**/
public CmsContainerElementBean(
CmsUUID elementId,
CmsUUID formatterId,
Map<String, String> individualSettings,
boolean createNew) {
m_elementId = elementId;
m_formatterId = formatterId;
Map<String, String> newSettings = (individualSettings == null
? new HashMap<String, String>()
: new HashMap<String, String>(individualSettings));
if (!newSettings.containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID)) {
newSettings.put(CmsContainerElement.ELEMENT_INSTANCE_ID, new CmsUUID().toString());
}
m_individualSettings = Collections.unmodifiableMap(newSettings);
m_editorHash = m_elementId.toString() + getSettingsHash();
m_createNew = createNew;
}
/**
* Constructor to enable wrapped elements.<p>
*/
protected CmsContainerElementBean() {
m_elementId = null;
m_createNew = false;
}
/**
* Cloning constructor.<p>
*
* @param createNew create new flag
* @param elementId element id
* @param formatterId formatter id
* @param individualSettings individual settings
* @param inheritanceInfo inheritance info
* @param inMemoryOnly in memory only flag
* @param temporaryContent temporary content flag
* @param releasedAndNotExpired released and not expired flag
* @param resource the resource/file object
* @param settings the settings
* @param sitePath the site path
*/
private CmsContainerElementBean(
boolean createNew,
CmsUUID elementId,
CmsUUID formatterId,
Map<String, String> individualSettings,
CmsInheritanceInfo inheritanceInfo,
boolean inMemoryOnly,
boolean temporaryContent,
boolean releasedAndNotExpired,
CmsResource resource,
Map<String, String> settings,
String sitePath) {
m_createNew = createNew;
m_elementId = elementId;
m_formatterId = formatterId;
m_individualSettings = Collections.unmodifiableMap(individualSettings);
m_inheritanceInfo = inheritanceInfo;
m_inMemoryOnly = inMemoryOnly;
m_releasedAndNotExpired = releasedAndNotExpired;
m_resource = resource;
m_settings = settings;
m_sitePath = sitePath;
m_temporaryContent = temporaryContent;
}
/**
* Clones the given element bean with a different set of settings.<p>
*
* @param source the element to clone
* @param settings the new settings
*
* @return the element bean
*/
public static CmsContainerElementBean cloneWithSettings(CmsContainerElementBean source, Map<String, String> settings) {
boolean createNew = source.m_createNew;
if (settings.containsKey(CmsContainerElement.CREATE_AS_NEW)) {
createNew = Boolean.valueOf(settings.get(CmsContainerElement.CREATE_AS_NEW)).booleanValue();
settings = new HashMap<String, String>(settings);
settings.remove(CmsContainerElement.CREATE_AS_NEW);
}
CmsContainerElementBean result = new CmsContainerElementBean(
source.m_elementId,
source.m_formatterId,
settings,
createNew);
result.m_resource = source.m_resource;
result.m_sitePath = source.m_sitePath;
result.m_inMemoryOnly = source.m_inMemoryOnly;
result.m_inheritanceInfo = source.m_inheritanceInfo;
if (result.m_inMemoryOnly) {
String editorHash = source.m_editorHash;
if (editorHash.contains(CmsADEManager.CLIENT_ID_SEPERATOR)) {
editorHash = editorHash.substring(0, editorHash.indexOf(CmsADEManager.CLIENT_ID_SEPERATOR));
}
editorHash += result.getSettingsHash();
result.m_editorHash = editorHash;
}
return result;
}
/**
* Creates an element bean for the given resource type.<p>
* <b>The represented resource will be in memory only and not in the VFS!!!.</b><p>
*
* @param cms the CMS context
* @param resourceType the resource type
* @param targetFolder the parent folder of the resource
* @param individualSettings the element settings as a map of name/value pairs
* @param isCopyModels if this element when used in models should be copied instead of reused
* @param locale the locale to use
*
* @return the created element bean
* @throws CmsException if something goes wrong creating the element
* @throws IllegalArgumentException if the resource type not instance of {@link org.opencms.file.types.CmsResourceTypeXmlContent}
*/
public static CmsContainerElementBean createElementForResourceType(
CmsObject cms,
I_CmsResourceType resourceType,
String targetFolder,
Map<String, String> individualSettings,
boolean isCopyModels,
Locale locale) throws CmsException {
if (!(resourceType instanceof CmsResourceTypeXmlContent)) {
throw new IllegalArgumentException();
}
CmsContainerElementBean elementBean = new CmsContainerElementBean(
CmsUUID.getNullUUID(),
null,
individualSettings,
!isCopyModels);
elementBean.m_inMemoryOnly = true;
elementBean.m_editorHash = resourceType.getTypeName() + elementBean.getSettingsHash();
byte[] content = new byte[0];
String schema = ((CmsResourceTypeXmlContent)resourceType).getSchema();
if (schema != null) {
// must set URI of OpenCms user context to parent folder of created resource,
// in order to allow reading of properties for default values
CmsObject newCms = OpenCms.initCmsObject(cms);
newCms.getRequestContext().setUri(targetFolder);
// unmarshal the content definition for the new resource
CmsXmlContentDefinition contentDefinition = CmsXmlContentDefinition.unmarshal(cms, schema);
CmsXmlContent xmlContent = CmsXmlContentFactory.createDocument(
newCms,
locale,
OpenCms.getSystemInfo().getDefaultEncoding(),
contentDefinition);
// adding all other available locales
for (Locale otherLocale : OpenCms.getLocaleManager().getAvailableLocales()) {
if (!locale.equals(otherLocale)) {
xmlContent.addLocale(newCms, otherLocale);
}
}
content = xmlContent.marshal();
}
elementBean.m_resource = new CmsFile(
CmsUUID.getNullUUID(),
CmsUUID.getNullUUID(),
targetFolder + "~",
resourceType.getTypeId(),
0,
cms.getRequestContext().getCurrentProject().getUuid(),
CmsResource.STATE_NEW,
0,
cms.getRequestContext().getCurrentUser().getId(),
0,
cms.getRequestContext().getCurrentUser().getId(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
1,
content.length,
0,
0,
content);
return elementBean;
}
/**
* @see java.lang.Object#clone()
*/
@Override
public CmsContainerElementBean clone() {
return new CmsContainerElementBean(
m_createNew,
m_elementId,
m_formatterId,
m_individualSettings,
m_inheritanceInfo,
m_inMemoryOnly,
m_temporaryContent,
m_releasedAndNotExpired,
m_resource,
m_settings,
m_sitePath);
}
/**
* Returns the ADE client editor has value.<p>
*
* @return the ADE client editor has value
*/
public String editorHash() {
return m_editorHash;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CmsContainerElementBean)) {
return false;
}
return editorHash().equals(((CmsContainerElementBean)obj).editorHash());
}
/**
* Returns the structure id of the formatter of this element.<p>
*
* @return the structure id of the formatter of this element
*/
public CmsUUID getFormatterId() {
return m_formatterId;
}
/**
* Returns the structure id of the resource of this element.<p>
*
* @return the structure id of the resource of this element
*/
public CmsUUID getId() {
return m_elementId;
}
/**
* Returns the settings of this element.<p>
*
* @return the settings of this element
*/
public Map<String, String> getIndividualSettings() {
return m_individualSettings;
}
/**
* Returns the inheritance info.<p>
*
* @return the inheritance info or <code>null</code> if not available
*/
public CmsInheritanceInfo getInheritanceInfo() {
return m_inheritanceInfo;
}
/**
* Returns the element instance id.<p>
*
* @return the element instance id
*/
public String getInstanceId() {
return getIndividualSettings().get(CmsContainerElement.ELEMENT_INSTANCE_ID);
}
/**
* Returns the resource of this element.<p>
*
* It is required to call {@link #initResource(CmsObject)} before this method can be used.<p>
*
* @return the resource of this element
*
* @see #initResource(CmsObject)
*/
public CmsResource getResource() {
return m_resource;
}
/**
* Returns the element settings including default values for settings not set.<p>
* Will return <code>null</code> if the element bean has not been initialized with {@link #initResource(org.opencms.file.CmsObject)}.<p>
*
* @return the element settings
*/
public Map<String, String> getSettings() {
return m_settings;
}
/**
* Returns the site path of the resource of this element.<p>
*
* It is required to call {@link #initResource(CmsObject)} before this method can be used.<p>
*
* @return the site path of the resource of this element
*
* @see #initResource(CmsObject)
*/
public String getSitePath() {
return m_sitePath;
}
/**
* Returns the resource type name.<p>
*
* @return the type name
*/
public String getTypeName() {
if (getResource() != null) {
return OpenCms.getResourceManager().getResourceType(getResource()).getTypeName();
} else {
return "unknown";
}
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return m_editorHash.hashCode();
}
/**
* Initializes the resource and the site path of this element.<p>
*
* @param cms the CMS context
*
* @throws CmsException if something goes wrong reading the element resource
*/
public void initResource(CmsObject cms) throws CmsException {
if (m_resource == null) {
m_resource = cms.readResource(getId(), CmsResourceFilter.IGNORE_EXPIRATION);
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
} else if (!isInMemoryOnly()) {
CmsUUID id = m_resource.getStructureId();
if (id == null) {
id = getId();
}
// the resource object may have a wrong root path, e.g. if it was created before the resource was moved
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
m_resource = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
} else {
if (!isTemporaryContent()) {
m_resource = cms.readResource(getId(), CmsResourceFilter.IGNORE_EXPIRATION);
}
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
}
}
if (m_settings == null) {
m_settings = new HashMap<String, String>(getIndividualSettings());
}
// redo on every init call to ensure sitepath is calculated for current site
m_sitePath = cms.getSitePath(m_resource);
}
/**
* Initializes the element settings.<p>
*
* @param cms the CMS context
* @param formatterBean the formatter configuration bean
*/
public void initSettings(CmsObject cms, I_CmsFormatterBean formatterBean) {
Map<String, String> mergedSettings;
if (formatterBean == null) {
mergedSettings = CmsXmlContentPropertyHelper.mergeDefaults(cms, m_resource, getIndividualSettings());
} else {
mergedSettings = CmsXmlContentPropertyHelper.mergeDefaults(
cms,
formatterBean.getSettings(),
getIndividualSettings());
}
if (m_settings == null) {
m_settings = mergedSettings;
} else {
m_settings.putAll(mergedSettings);
}
}
/**
* Returns if the given element should be used as a copy model.<p>
*
* @return <code>true</code> if the given element should be used as a copy model
*/
public boolean isCopyModel() {
return Boolean.valueOf(getIndividualSettings().get(CmsContainerElement.USE_AS_COPY_MODEL)).booleanValue();
}
/**
* Returns if a new element should be created replacing the given one on first edit of a container-page.<p>
*
* @return <code>true</code> if a new element should be created replacing the given one on first edit of a container-page
*/
public boolean isCreateNew() {
return m_createNew;
}
/**
* Tests whether this element refers to a group container.<p>
*
* @param cms the CmsObject used for VFS operations
*
* @return <code>true</code> if the container element refers to a group container
*
* @throws CmsException if something goes wrong
*/
public boolean isGroupContainer(CmsObject cms) throws CmsException {
if (m_resource == null) {
initResource(cms);
}
return CmsResourceTypeXmlContainerPage.GROUP_CONTAINER_TYPE_NAME.equals(OpenCms.getResourceManager().getResourceType(
m_resource).getTypeName());
}
/**
* Returns whether this element refers to an inherited container element.<p>
*
* @param cms the CmsObject used for VFS operations
*
* @return <code>true</code> if the container element refers to an inherited container
*
* @throws CmsException if something goes wrong
*/
public boolean isInheritedContainer(CmsObject cms) throws CmsException {
if (m_resource == null) {
initResource(cms);
}
return OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlContainerPage.INHERIT_CONTAINER_TYPE_NAME).getTypeId() == m_resource.getTypeId();
}
/**
* Returns if the represented resource is in memory only and not persisted in the VFS.<p>
*
* @return <code>true</code> if the represented resource is in memory only and not persisted in the VFS
*/
public boolean isInMemoryOnly() {
return m_inMemoryOnly;
}
/**
* Returns if the given element is a model group.<p>
*
* @return <code>true</code> if the given element is a model group
*/
public boolean isModelGroup() {
ModelGroupState state = ModelGroupState.evaluate(getIndividualSettings().get(
CmsContainerElement.MODEL_GROUP_STATE));
return state == ModelGroupState.isModelGroup;
}
/**
* Returns if all instances of this element should be replaced within a copy model.<p>
*
* @return <code>true</code> if all instances of this element should be replaced within a copy model
*/
public boolean isModelGroupAlwaysReplace() {
return Boolean.parseBoolean(getIndividualSettings().get(CmsContainerElement.IS_MODEL_GROUP_ALWAYS_REPLACE));
}
/**
* Returns if the element resource is released and not expired.<p>
*
* @return <code>true</code> if the element resource is released and not expired
*/
public boolean isReleasedAndNotExpired() {
return isInMemoryOnly() || m_releasedAndNotExpired;
}
/**
* Returns if the element resource contains temporary file content.<p>
*
* @return <code>true</code> if the element resource contains temporary file content
*/
public boolean isTemporaryContent() {
return m_temporaryContent;
}
/**
* Removes the instance id.<p>
*/
public void removeInstanceId() {
Map<String, String> newSettings = new HashMap<String, String>(m_individualSettings);
newSettings.remove(CmsContainerElement.ELEMENT_INSTANCE_ID);
m_individualSettings = Collections.unmodifiableMap(newSettings);
m_editorHash = m_elementId.toString() + getSettingsHash();
}
/**
* Sets the formatter id.<p>
*
* @param formatterId the formatter id
*/
public void setFormatterId(CmsUUID formatterId) {
m_formatterId = formatterId;
}
/**
* Sets a historical file.<p>
*
* @param file the historical file
*/
public void setHistoryFile(CmsFile file) {
m_resource = file;
m_inMemoryOnly = true;
}
/**
* Sets the inheritance info for this element.<p>
*
* @param inheritanceInfo the inheritance info
*/
public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) {
m_inheritanceInfo = inheritanceInfo;
}
/**
* Sets the element resource as a temporary file.<p>
*
* @param elementFile the temporary file
*/
public void setTemporaryFile(CmsFile elementFile) {
m_resource = elementFile;
m_temporaryContent = true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return editorHash();
}
/**
* Gets the hash code for the element settings.<p>
*
* @return the hash code for the element settings
*/
private String getSettingsHash() {
if (!getIndividualSettings().isEmpty() || m_createNew) {
int hash = (getIndividualSettings().toString() + m_createNew).hashCode();
return CmsADEManager.CLIENT_ID_SEPERATOR + hash;
}
return "";
}
}
| src/org/opencms/xml/containerpage/CmsContainerElementBean.java | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.xml.containerpage;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.containerpage.shared.CmsContainerElement;
import org.opencms.ade.containerpage.shared.CmsContainerElement.ModelGroupState;
import org.opencms.ade.containerpage.shared.CmsInheritanceInfo;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsUUID;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentPropertyHelper;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* One element of a container in a container page.<p>
*
* @since 8.0
*/
public class CmsContainerElementBean implements Cloneable {
/** Flag indicating if a new element should be created replacing the given one on first edit of a container-page. */
private final boolean m_createNew;
/** The client ADE editor hash. */
private transient String m_editorHash;
/** The element's structure id. */
private CmsUUID m_elementId;
/** The formatter's structure id. */
private CmsUUID m_formatterId;
/** The configured properties. */
private Map<String, String> m_individualSettings;
/** The inheritance info of this element. */
private CmsInheritanceInfo m_inheritanceInfo;
/** Indicates whether the represented resource is in memory only and not in the VFS. */
private boolean m_inMemoryOnly;
/** Indicating if the element resource is released and not expired. */
private boolean m_releasedAndNotExpired;
/** The resource of this element. */
private transient CmsResource m_resource;
/** The settings of this element containing also default values. */
private transient Map<String, String> m_settings;
/** The element site path, only set while rendering. */
private String m_sitePath;
/** Indicates the element bean has a temporary file content set. */
private boolean m_temporaryContent;
/**
* Creates a new container page element bean.<p>
*
* @param elementId the element's structure id
* @param formatterId the formatter's structure id, could be <code>null</code>
* @param individualSettings the element settings as a map of name/value pairs
* @param createNew <code>true</code> if a new element should be created replacing the given one on first edit of a container-page
**/
public CmsContainerElementBean(
CmsUUID elementId,
CmsUUID formatterId,
Map<String, String> individualSettings,
boolean createNew) {
m_elementId = elementId;
m_formatterId = formatterId;
Map<String, String> newSettings = (individualSettings == null
? new HashMap<String, String>()
: new HashMap<String, String>(individualSettings));
if (!newSettings.containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID)) {
newSettings.put(CmsContainerElement.ELEMENT_INSTANCE_ID, new CmsUUID().toString());
}
m_individualSettings = Collections.unmodifiableMap(newSettings);
m_editorHash = m_elementId.toString() + getSettingsHash();
m_createNew = createNew;
}
/**
* Constructor to enable wrapped elements.<p>
*/
protected CmsContainerElementBean() {
m_elementId = null;
m_createNew = false;
}
/**
* Cloning constructor.<p>
*
* @param createNew create new flag
* @param elementId element id
* @param formatterId formatter id
* @param individualSettings individual settings
* @param inheritanceInfo inheritance info
* @param inMemoryOnly in memory only flag
* @param temporaryContent temporary content flag
* @param releasedAndNotExpired released and not expired flag
* @param resource the resource/file object
* @param settings the settings
* @param sitePath the site path
*/
private CmsContainerElementBean(
boolean createNew,
CmsUUID elementId,
CmsUUID formatterId,
Map<String, String> individualSettings,
CmsInheritanceInfo inheritanceInfo,
boolean inMemoryOnly,
boolean temporaryContent,
boolean releasedAndNotExpired,
CmsResource resource,
Map<String, String> settings,
String sitePath) {
m_createNew = createNew;
m_elementId = elementId;
m_formatterId = formatterId;
m_individualSettings = Collections.unmodifiableMap(individualSettings);
m_inheritanceInfo = inheritanceInfo;
m_inMemoryOnly = inMemoryOnly;
m_releasedAndNotExpired = releasedAndNotExpired;
m_resource = resource;
m_settings = settings;
m_sitePath = sitePath;
m_temporaryContent = temporaryContent;
}
/**
* Clones the given element bean with a different set of settings.<p>
*
* @param source the element to clone
* @param settings the new settings
*
* @return the element bean
*/
public static CmsContainerElementBean cloneWithSettings(CmsContainerElementBean source, Map<String, String> settings) {
boolean createNew = source.m_createNew;
if (settings.containsKey(CmsContainerElement.CREATE_AS_NEW)) {
createNew = Boolean.valueOf(settings.get(CmsContainerElement.CREATE_AS_NEW)).booleanValue();
settings = new HashMap<String, String>(settings);
settings.remove(CmsContainerElement.CREATE_AS_NEW);
}
CmsContainerElementBean result = new CmsContainerElementBean(
source.m_elementId,
source.m_formatterId,
settings,
createNew);
result.m_resource = source.m_resource;
result.m_sitePath = source.m_sitePath;
result.m_inMemoryOnly = source.m_inMemoryOnly;
result.m_inheritanceInfo = source.m_inheritanceInfo;
if (result.m_inMemoryOnly) {
String editorHash = source.m_editorHash;
if (editorHash.contains(CmsADEManager.CLIENT_ID_SEPERATOR)) {
editorHash = editorHash.substring(0, editorHash.indexOf(CmsADEManager.CLIENT_ID_SEPERATOR));
}
editorHash += result.getSettingsHash();
result.m_editorHash = editorHash;
}
return result;
}
/**
* Creates an element bean for the given resource type.<p>
* <b>The represented resource will be in memory only and not in the VFS!!!.</b><p>
*
* @param cms the CMS context
* @param resourceType the resource type
* @param targetFolder the parent folder of the resource
* @param individualSettings the element settings as a map of name/value pairs
* @param isCopyModels if this element when used in models should be copied instead of reused
* @param locale the locale to use
*
* @return the created element bean
* @throws CmsException if something goes wrong creating the element
* @throws IllegalArgumentException if the resource type not instance of {@link org.opencms.file.types.CmsResourceTypeXmlContent}
*/
public static CmsContainerElementBean createElementForResourceType(
CmsObject cms,
I_CmsResourceType resourceType,
String targetFolder,
Map<String, String> individualSettings,
boolean isCopyModels,
Locale locale) throws CmsException {
if (!(resourceType instanceof CmsResourceTypeXmlContent)) {
throw new IllegalArgumentException();
}
CmsContainerElementBean elementBean = new CmsContainerElementBean(
CmsUUID.getNullUUID(),
null,
individualSettings,
!isCopyModels);
elementBean.m_inMemoryOnly = true;
elementBean.m_editorHash = resourceType.getTypeName() + elementBean.getSettingsHash();
byte[] content = new byte[0];
String schema = ((CmsResourceTypeXmlContent)resourceType).getSchema();
if (schema != null) {
// must set URI of OpenCms user context to parent folder of created resource,
// in order to allow reading of properties for default values
CmsObject newCms = OpenCms.initCmsObject(cms);
newCms.getRequestContext().setUri(targetFolder);
// unmarshal the content definition for the new resource
CmsXmlContentDefinition contentDefinition = CmsXmlContentDefinition.unmarshal(cms, schema);
CmsXmlContent xmlContent = CmsXmlContentFactory.createDocument(
newCms,
locale,
OpenCms.getSystemInfo().getDefaultEncoding(),
contentDefinition);
// adding all other available locales
for (Locale otherLocale : OpenCms.getLocaleManager().getAvailableLocales()) {
if (!locale.equals(otherLocale)) {
xmlContent.addLocale(newCms, otherLocale);
}
}
content = xmlContent.marshal();
}
elementBean.m_resource = new CmsFile(
CmsUUID.getNullUUID(),
CmsUUID.getNullUUID(),
targetFolder + "~",
resourceType.getTypeId(),
0,
cms.getRequestContext().getCurrentProject().getUuid(),
CmsResource.STATE_NEW,
0,
cms.getRequestContext().getCurrentUser().getId(),
0,
cms.getRequestContext().getCurrentUser().getId(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
1,
content.length,
0,
0,
content);
return elementBean;
}
/**
* @see java.lang.Object#clone()
*/
@Override
public CmsContainerElementBean clone() {
return new CmsContainerElementBean(
m_createNew,
m_elementId,
m_formatterId,
m_individualSettings,
m_inheritanceInfo,
m_inMemoryOnly,
m_temporaryContent,
m_releasedAndNotExpired,
m_resource,
m_settings,
m_sitePath);
}
/**
* Returns the ADE client editor has value.<p>
*
* @return the ADE client editor has value
*/
public String editorHash() {
return m_editorHash;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CmsContainerElementBean)) {
return false;
}
return editorHash().equals(((CmsContainerElementBean)obj).editorHash());
}
/**
* Returns the structure id of the formatter of this element.<p>
*
* @return the structure id of the formatter of this element
*/
public CmsUUID getFormatterId() {
return m_formatterId;
}
/**
* Returns the structure id of the resource of this element.<p>
*
* @return the structure id of the resource of this element
*/
public CmsUUID getId() {
return m_elementId;
}
/**
* Returns the settings of this element.<p>
*
* @return the settings of this element
*/
public Map<String, String> getIndividualSettings() {
return m_individualSettings;
}
/**
* Returns the inheritance info.<p>
*
* @return the inheritance info or <code>null</code> if not available
*/
public CmsInheritanceInfo getInheritanceInfo() {
return m_inheritanceInfo;
}
/**
* Returns the element instance id.<p>
*
* @return the element instance id
*/
public String getInstanceId() {
return getIndividualSettings().get(CmsContainerElement.ELEMENT_INSTANCE_ID);
}
/**
* Returns the resource of this element.<p>
*
* It is required to call {@link #initResource(CmsObject)} before this method can be used.<p>
*
* @return the resource of this element
*
* @see #initResource(CmsObject)
*/
public CmsResource getResource() {
return m_resource;
}
/**
* Returns the element settings including default values for settings not set.<p>
* Will return <code>null</code> if the element bean has not been initialized with {@link #initResource(org.opencms.file.CmsObject)}.<p>
*
* @return the element settings
*/
public Map<String, String> getSettings() {
return m_settings;
}
/**
* Returns the site path of the resource of this element.<p>
*
* It is required to call {@link #initResource(CmsObject)} before this method can be used.<p>
*
* @return the site path of the resource of this element
*
* @see #initResource(CmsObject)
*/
public String getSitePath() {
return m_sitePath;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return m_editorHash.hashCode();
}
/**
* Initializes the resource and the site path of this element.<p>
*
* @param cms the CMS context
*
* @throws CmsException if something goes wrong reading the element resource
*/
public void initResource(CmsObject cms) throws CmsException {
if (m_resource == null) {
m_resource = cms.readResource(getId(), CmsResourceFilter.IGNORE_EXPIRATION);
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
} else if (!isInMemoryOnly()) {
CmsUUID id = m_resource.getStructureId();
if (id == null) {
id = getId();
}
// the resource object may have a wrong root path, e.g. if it was created before the resource was moved
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
m_resource = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
} else {
if (!isTemporaryContent()) {
m_resource = cms.readResource(getId(), CmsResourceFilter.IGNORE_EXPIRATION);
}
m_releasedAndNotExpired = m_resource.isReleasedAndNotExpired(cms.getRequestContext().getRequestTime());
}
}
if (m_settings == null) {
m_settings = new HashMap<String, String>(getIndividualSettings());
}
// redo on every init call to ensure sitepath is calculated for current site
m_sitePath = cms.getSitePath(m_resource);
}
/**
* Initializes the element settings.<p>
*
* @param cms the CMS context
* @param formatterBean the formatter configuration bean
*/
public void initSettings(CmsObject cms, I_CmsFormatterBean formatterBean) {
Map<String, String> mergedSettings;
if (formatterBean == null) {
mergedSettings = CmsXmlContentPropertyHelper.mergeDefaults(cms, m_resource, getIndividualSettings());
} else {
mergedSettings = CmsXmlContentPropertyHelper.mergeDefaults(
cms,
formatterBean.getSettings(),
getIndividualSettings());
}
if (m_settings == null) {
m_settings = mergedSettings;
} else {
m_settings.putAll(mergedSettings);
}
}
/**
* Returns if the given element should be used as a copy model.<p>
*
* @return <code>true</code> if the given element should be used as a copy model
*/
public boolean isCopyModel() {
return Boolean.valueOf(getIndividualSettings().get(CmsContainerElement.USE_AS_COPY_MODEL)).booleanValue();
}
/**
* Returns if a new element should be created replacing the given one on first edit of a container-page.<p>
*
* @return <code>true</code> if a new element should be created replacing the given one on first edit of a container-page
*/
public boolean isCreateNew() {
return m_createNew;
}
/**
* Tests whether this element refers to a group container.<p>
*
* @param cms the CmsObject used for VFS operations
*
* @return <code>true</code> if the container element refers to a group container
*
* @throws CmsException if something goes wrong
*/
public boolean isGroupContainer(CmsObject cms) throws CmsException {
if (m_resource == null) {
initResource(cms);
}
return CmsResourceTypeXmlContainerPage.GROUP_CONTAINER_TYPE_NAME.equals(OpenCms.getResourceManager().getResourceType(
m_resource).getTypeName());
}
/**
* Returns whether this element refers to an inherited container element.<p>
*
* @param cms the CmsObject used for VFS operations
*
* @return <code>true</code> if the container element refers to an inherited container
*
* @throws CmsException if something goes wrong
*/
public boolean isInheritedContainer(CmsObject cms) throws CmsException {
if (m_resource == null) {
initResource(cms);
}
return OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlContainerPage.INHERIT_CONTAINER_TYPE_NAME).getTypeId() == m_resource.getTypeId();
}
/**
* Returns if the represented resource is in memory only and not persisted in the VFS.<p>
*
* @return <code>true</code> if the represented resource is in memory only and not persisted in the VFS
*/
public boolean isInMemoryOnly() {
return m_inMemoryOnly;
}
/**
* Returns if the given element is a model group.<p>
*
* @return <code>true</code> if the given element is a model group
*/
public boolean isModelGroup() {
ModelGroupState state = ModelGroupState.evaluate(getIndividualSettings().get(
CmsContainerElement.MODEL_GROUP_STATE));
return state == ModelGroupState.isModelGroup;
}
/**
* Returns if all instances of this element should be replaced within a copy model.<p>
*
* @return <code>true</code> if all instances of this element should be replaced within a copy model
*/
public boolean isModelGroupAlwaysReplace() {
return Boolean.parseBoolean(getIndividualSettings().get(CmsContainerElement.IS_MODEL_GROUP_ALWAYS_REPLACE));
}
/**
* Returns if the element resource is released and not expired.<p>
*
* @return <code>true</code> if the element resource is released and not expired
*/
public boolean isReleasedAndNotExpired() {
return isInMemoryOnly() || m_releasedAndNotExpired;
}
/**
* Returns if the element resource contains temporary file content.<p>
*
* @return <code>true</code> if the element resource contains temporary file content
*/
public boolean isTemporaryContent() {
return m_temporaryContent;
}
/**
* Removes the instance id.<p>
*/
public void removeInstanceId() {
Map<String, String> newSettings = new HashMap<String, String>(m_individualSettings);
newSettings.remove(CmsContainerElement.ELEMENT_INSTANCE_ID);
m_individualSettings = Collections.unmodifiableMap(newSettings);
m_editorHash = m_elementId.toString() + getSettingsHash();
}
/**
* Sets the formatter id.<p>
*
* @param formatterId the formatter id
*/
public void setFormatterId(CmsUUID formatterId) {
m_formatterId = formatterId;
}
/**
* Sets a historical file.<p>
*
* @param file the historical file
*/
public void setHistoryFile(CmsFile file) {
m_resource = file;
m_inMemoryOnly = true;
}
/**
* Sets the inheritance info for this element.<p>
*
* @param inheritanceInfo the inheritance info
*/
public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) {
m_inheritanceInfo = inheritanceInfo;
}
/**
* Sets the element resource as a temporary file.<p>
*
* @param elementFile the temporary file
*/
public void setTemporaryFile(CmsFile elementFile) {
m_resource = elementFile;
m_temporaryContent = true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return editorHash();
}
/**
* Gets the hash code for the element settings.<p>
*
* @return the hash code for the element settings
*/
private String getSettingsHash() {
if (!getIndividualSettings().isEmpty() || m_createNew) {
int hash = (getIndividualSettings().toString() + m_createNew).hashCode();
return CmsADEManager.CLIENT_ID_SEPERATOR + hash;
}
return "";
}
}
| Added convenience method to get the element resource type name. | src/org/opencms/xml/containerpage/CmsContainerElementBean.java | Added convenience method to get the element resource type name. | <ide><path>rc/org/opencms/xml/containerpage/CmsContainerElementBean.java
<ide> }
<ide>
<ide> /**
<add> * Returns the resource type name.<p>
<add> *
<add> * @return the type name
<add> */
<add> public String getTypeName() {
<add>
<add> if (getResource() != null) {
<add> return OpenCms.getResourceManager().getResourceType(getResource()).getTypeName();
<add> } else {
<add> return "unknown";
<add> }
<add> }
<add>
<add> /**
<ide> * @see java.lang.Object#hashCode()
<ide> */
<ide> @Override |
|
Java | apache-2.0 | dbd9b4b0710f3ab59ed9fe2ac9638d1ee615de8c | 0 | mikaelkindborg/cordova-ble,evothings/cordova-ble,divineprog/cordova-ble,divineprog/cordova-ble,mikaelkindborg/cordova-ble,evothings/cordova-ble,divineprog/cordova-ble,mikaelkindborg/cordova-ble,evothings/cordova-ble | /*
Copyright 2014 Evothings AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.evothings;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.*;
import android.bluetooth.le.*;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.*;
import android.app.Activity;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.*;
import android.util.Base64;
import android.os.ParcelUuid;
import android.util.Log;
import android.content.pm.PackageManager;
import android.os.Build;
import android.Manifest;
public class BLE
extends CordovaPlugin
implements
LeScanCallback
{
// ************* BLE CENTRAL ROLE *************
// Implementation of BLE Central API.
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
// Used by startScan().
private CallbackContext mScanCallbackContext;
private CordovaArgs mScanArgs;
// Used by reset().
private CallbackContext mResetCallbackContext;
// The Android application Context.
private Context mContext;
private boolean mRegisteredReceiver = false;
// Called when the device's Bluetooth powers on.
// Used by startScan() and connect() to wait for power-on if Bluetooth was
// off when the function was called.
private Runnable mOnPowerOn;
// Used to send error messages to the JavaScript side if Bluetooth power-on fails.
private CallbackContext mPowerOnCallbackContext;
// Map of connected devices.
HashMap<Integer, GattHandler> mConnectedDevices = null;
// Monotonically incrementing key to the Gatt map.
int mNextGattHandle = 1;
// Called each time cordova.js is loaded.
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
mContext = webView.getContext();
if(!mRegisteredReceiver) {
mContext.registerReceiver(
new BluetoothStateReceiver(),
new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
mRegisteredReceiver = true;
}
}
// Handles JavaScript-to-native function calls.
// Returns true if a supported function was called, false otherwise.
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
{
try {
if("startScan".equals(action)) { startScan(args, callbackContext); return true; }
else if("stopScan".equals(action)) { stopScan(args, callbackContext); return true; }
else if("connect".equals(action)) { connect(args, callbackContext); return true; }
else if("close".equals(action)) { close(args, callbackContext); return true; }
else if("rssi".equals(action)) { rssi(args, callbackContext); return true; }
else if("services".equals(action)) { services(args, callbackContext); return true; }
else if("characteristics".equals(action)) { characteristics(args, callbackContext); return true; }
else if("descriptors".equals(action)) { descriptors(args, callbackContext); return true; }
else if("readCharacteristic".equals(action)) { readCharacteristic(args, callbackContext); return true; }
else if("readDescriptor".equals(action)) { readDescriptor(args, callbackContext); return true; }
else if("writeCharacteristic".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); return true; }
else if("writeCharacteristicWithoutResponse".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); return true; }
else if("writeDescriptor".equals(action)) { writeDescriptor(args, callbackContext); return true; }
else if("enableNotification".equals(action)) { enableNotification(args, callbackContext); return true; }
else if("disableNotification".equals(action)) { disableNotification(args, callbackContext); return true; }
else if("testCharConversion".equals(action)) { testCharConversion(args, callbackContext); return true; }
else if("reset".equals(action)) { reset(args, callbackContext); return true; }
else if("startAdvertise".equals(action)) { startAdvertise(args, callbackContext); return true; }
else if("stopAdvertise".equals(action)) { stopAdvertise(args, callbackContext); return true; }
else if("startGattServer".equals(action)) { startGattServer(args, callbackContext); return true; }
else if("stopGattServer".equals(action)) { stopGattServer(args, callbackContext); return true; }
else if("sendResponse".equals(action)) { sendResponse(args, callbackContext); return true; }
else if("notify".equals(action)) { notify(args, callbackContext); return true; }
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
}
return false;
}
/**
* Called when the WebView does a top-level navigation or refreshes.
*
* Plugins should stop any long-running processes and clean up internal state.
*
* Does nothing by default.
*
* Our version should stop any ongoing scan, and close any existing connections.
*/
@Override
public void onReset()
{
if(mScanCallbackContext != null) {
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
a.stopLeScan(this);
mScanCallbackContext = null;
}
if(mConnectedDevices != null) {
Iterator<GattHandler> itr = mConnectedDevices.values().iterator();
while(itr.hasNext()) {
GattHandler gh = itr.next();
if(gh.mGatt != null)
gh.mGatt.close();
}
mConnectedDevices.clear();
}
if(mGattServer != null) {
mGattServer.close();
mGattServer = null;
}
}
// Possibly asynchronous.
// Ensures Bluetooth is powered on, then calls the Runnable \a onPowerOn.
// Calls cc.error if power-on fails.
private void checkPowerState(BluetoothAdapter adapter, CallbackContext cc, Runnable onPowerOn)
{
if(adapter == null) {
cc.error("Bluetooth not supported");
return;
}
if(adapter.getState() == BluetoothAdapter.STATE_ON) {
// Bluetooth is ON
onPowerOn.run();
} else {
mOnPowerOn = onPowerOn;
mPowerOnCallbackContext = cc;
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
cordova.startActivityForResult(this, enableBtIntent, 0);
}
}
// Called whe the Bluetooth power-on request is completed.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Runnable onPowerOn = mOnPowerOn;
CallbackContext cc = mPowerOnCallbackContext;
mOnPowerOn = null;
mPowerOnCallbackContext = null;
if(resultCode == Activity.RESULT_OK) {
if (null != onPowerOn) {
onPowerOn.run();
} else {
// Runnable was null.
if (null != cc) cc.error("Runnable is null in onActivityResult (internal error)");
}
} else {
if(resultCode == Activity.RESULT_CANCELED) {
if (null != cc) cc.error("Bluetooth power-on canceled");
} else {
if (null != cc) cc.error("Bluetooth power-on failed with code: "+resultCode);
}
}
}
// These three functions each send a JavaScript callback *without* removing
// the callback context, as is default.
private void keepCallback(final CallbackContext callbackContext, JSONObject message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, String message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, byte[] message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
// Callback from cordova.requestPermissions().
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
//Log.i("@@@@@@@@", "onRequestPermissionsResult: " + permissions + " " + grantResults);
if (PERMISSION_REQUEST_COARSE_LOCATION == requestCode)
{
if (PackageManager.PERMISSION_GRANTED == grantResults[0])
{
//Log.i("@@@@@@@@", "Coarse location permission granted");
// Permission ok, start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
else
{
//Log.i("@@@@@@@@", "Coarse location permission NOT granted");
// Permission NOT ok, send callback error.
mScanCallbackContext.error("Location permission not granted");
mScanCallbackContext = null;
}
}
}
// API implementation. See ble.js for documentation.
private void startScan(final CordovaArgs args, final CallbackContext callbackContext)
{
// Save callback context.
mScanCallbackContext = callbackContext;
mScanArgs = args;
// Cordova Permission check
if (!cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
{
//Log.i("@@@@@@@@", "PERMISSION NEEDED");
// Permission needed. Ask user.
cordova.requestPermission(this, PERMISSION_REQUEST_COARSE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION);
return;
}
// Permission ok, go ahead and start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
private void startScanImpl(final CordovaArgs args, final CallbackContext callbackContext)
{
//Log.i("@@@@@@", "Start scan");
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final LeScanCallback self = this;
// Get service UUIDs.
UUID[] uuidArray = null;
try
{
JSONArray uuids = args.getJSONArray(0);
if (null != uuids)
{
uuidArray = new UUID[uuids.length()];
for (int i = 0; i < uuids.length(); ++i)
{
uuidArray[i] = UUID.fromString(uuids.getString(i));
}
}
}
catch(JSONException ex)
{
uuidArray = null;
}
final UUID[] serviceUUIDs = uuidArray;
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
if(!adapter.startLeScan(serviceUUIDs, self))
{
//Log.i("@@@@@@", "Start scan failed");
callbackContext.error("Android function startLeScan failed");
mScanCallbackContext = null;
return;
}
}
});
}
// Called during scan, when a device advertisement is received.
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
//Log.i("@@@@@@", "onLeScan");
if (mScanCallbackContext == null)
{
return;
}
try
{
//Log.i("@@@@@@", "onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
//System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("address", device.getAddress());
jsonObject.put("rssi", rssi);
jsonObject.put("name", device.getName());
jsonObject.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
keepCallback(mScanCallbackContext, jsonObject);
}
catch(JSONException e)
{
mScanCallbackContext.error(e.toString());
}
}
// API implementation.
private void stopScan(final CordovaArgs args, final CallbackContext callbackContext)
{
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.stopLeScan(this);
mScanCallbackContext = null;
}
// API implementation.
private void connect(final CordovaArgs args, final CallbackContext callbackContext)
{
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
try {
// Each device connection has a GattHandler, which handles the events the can happen to the connection.
// The implementation of the GattHandler class is found at the end of this file.
GattHandler gh = new GattHandler(mNextGattHandle, callbackContext);
gh.mGatt = adapter.getRemoteDevice(args.getString(0)).connectGatt(mContext, true, gh);
// Note that gh.mGatt and this.mGatt are different object and have different types.
// --> Renamed this.mGatt to mConnectedDevices to avoid confusion.
if(mConnectedDevices == null)
mConnectedDevices = new HashMap<Integer, GattHandler>();
Object res = mConnectedDevices.put(mNextGattHandle, gh);
assert(res == null);
mNextGattHandle++;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
});
}
// API implementation.
private void close(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mGatt.close();
mConnectedDevices.remove(args.getInt(0));
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void rssi(final CordovaArgs args, final CallbackContext callbackContext)
{
GattHandler gh = null;
try {
gh = mConnectedDevices.get(args.getInt(0));
if(gh.mRssiContext != null) {
callbackContext.error("Previous call to rssi() not yet completed!");
return;
}
gh.mRssiContext = callbackContext;
if(!gh.mGatt.readRemoteRssi()) {
gh.mRssiContext = null;
callbackContext.error("readRemoteRssi");
}
} catch(Exception e) {
e.printStackTrace();
if(gh != null) {
gh.mRssiContext = null;
}
callbackContext.error(e.toString());
}
}
// API implementation.
private void services(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.discoverServices()) {
gh.mCurrentOpContext = null;
callbackContext.error("discoverServices");
gh.process();
}
}
});
gh.process();
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void characteristics(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattCharacteristic c : gh.mServices.get(args.getInt(1)).getCharacteristics()) {
if(gh.mCharacteristics == null)
gh.mCharacteristics = new HashMap<Integer, BluetoothGattCharacteristic>();
Object res = gh.mCharacteristics.put(gh.mNextHandle, c);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", c.getUuid().toString());
o.put("permissions", c.getPermissions());
o.put("properties", c.getProperties());
o.put("writeType", c.getWriteType());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void descriptors(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattDescriptor d : gh.mCharacteristics.get(args.getInt(1)).getDescriptors()) {
if(gh.mDescriptors == null)
gh.mDescriptors = new HashMap<Integer, BluetoothGattDescriptor>();
Object res = gh.mDescriptors.put(gh.mNextHandle, d);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", d.getUuid().toString());
o.put("permissions", d.getPermissions());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void readCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readCharacteristic(gh.mCharacteristics.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void readDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readDescriptor(gh.mDescriptors.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext,
final int writeType)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattCharacteristic c = gh.mCharacteristics.get(args.getInt(1));
System.out.println("writeCharacteristic("+args.getInt(0)+", "+args.getInt(1)+", "+args.getString(2)+")");
c.setWriteType(writeType);
c.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeCharacteristic(c)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattDescriptor d = gh.mDescriptors.get(args.getInt(1));
d.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeDescriptor(d)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// Notification options flag.
private final int NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG = 1;
// API implementation.
private void enableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification on.
boolean setConfigDescriptor = (options == 0);
turnNotificationOn(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// API implementation.
private void disableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification off.
boolean setConfigDescriptor = (options == 0);
turnNotificationOff(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// Helper method.
private void turnNotificationOn(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
if (setConfigDescriptor) {
// Write the config descriptor and enable notification.
if (enableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Enable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when enabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean enableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Config descriptor value.
byte[] descriptorValue;
// Check if notification or indication should be used.
if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
}
else if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
}
else {
callbackContext.error("Characteristic does not support notification or indication.");
gattHandler.process();
return false;
}
// Set value of config descriptor.
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void enableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification on.
boolean success = gatt.setCharacteristicNotification(characteristic, true);
if (!success) {
callbackContext.error("Could not enable notification");
gattHandler.process();
return;
}
// Save callback context for the characteristic.
// When turning notification on, the success callback will be
// called on every notification event.
gattHandler.mNotifications.put(characteristic, callbackContext);
}
// Helper method.
private void turnNotificationOff(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
// Remove callback context for the characteristic
// when turning off notification.
gattHandler.mNotifications.remove(characteristic);
if (setConfigDescriptor) {
// Write the config descriptor and disable notification.
if (disableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Disable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when disabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean disableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Set value of config descriptor.
byte[] descriptorValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void disableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification off.
boolean success = gatt.setCharacteristicNotification(characteristic, false);
if (!success) {
callbackContext.error("Could not disable notification");
gattHandler.process();
return;
}
// Call success callback when notification is turned off.
callbackContext.success();
}
// API implementation.
private void testCharConversion(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
byte[] b = {(byte)args.getInt(0)};
callbackContext.success(b);
}
// API implementation.
private void reset(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
mResetCallbackContext = null;
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
if(mScanCallbackContext != null) {
a.stopLeScan(this);
mScanCallbackContext = null;
}
int state = a.getState();
//STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF.
if(state == BluetoothAdapter.STATE_TURNING_ON) {
// reset in progress; wait for STATE_ON.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_TURNING_OFF) {
// reset in progress; wait for STATE_OFF.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("enable");
}
return;
}
if(state == BluetoothAdapter.STATE_ON) {
boolean res = a.disable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("disable");
}
return;
}
cc.error("Unknown state: "+state);
}
// Receives notification about Bluetooth power on and off. Used by reset().
class BluetoothStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
int state = a.getState();
System.out.println("BluetoothState: "+a);
if(mResetCallbackContext != null) {
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(!res) {
mResetCallbackContext.error("enable");
mResetCallbackContext = null;
}
}
if(state == BluetoothAdapter.STATE_ON) {
mResetCallbackContext.success();
mResetCallbackContext = null;
}
}
}
};
/* Running more than one operation of certain types on remote Gatt devices
* seem to cause it to stop responding.
* The known types are 'read' and 'write'.
* I've added 'services' to be on the safe side.
* 'rssi' and 'notification' should be safe.
*/
// This class handles callbacks pertaining to device connections.
// Also maintains the per-device operation queue.
private class GattHandler extends BluetoothGattCallback
{
// Local copy of the key to BLE.mGatt. Fed by BLE.mNextGattHandle.
final int mHandle;
// The queue of operations.
LinkedList<Runnable> mOperations = new LinkedList<Runnable>();
// connect() and rssi() are handled separately from other operations.
CallbackContext mConnectContext;
CallbackContext mRssiContext;
CallbackContext mCurrentOpContext;
// Special flag for doing async operations without a Cordova callback context.
// Used when writing notification config descriptor.
boolean mCurrentOp = false;
// The Android API connection.
BluetoothGatt mGatt;
// Maps of integer to Gatt subobject.
HashMap<Integer, BluetoothGattService> mServices;
HashMap<Integer, BluetoothGattCharacteristic> mCharacteristics;
HashMap<Integer, BluetoothGattDescriptor> mDescriptors;
// Monotonically incrementing key to the subobject maps.
int mNextHandle = 1;
// Notification callbacks. The BluetoothGattCharacteristic object, as found
// in the mCharacteristics map, is the key.
HashMap<BluetoothGattCharacteristic, CallbackContext> mNotifications =
new HashMap<BluetoothGattCharacteristic, CallbackContext>();
GattHandler(int h, CallbackContext cc)
{
mHandle = h;
mConnectContext = cc;
}
// Run the next operation, if any.
void process()
{
if(mCurrentOpContext != null || mCurrentOp)
return;
Runnable r = mOperations.poll();
if(r == null)
return;
r.run();
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
try {
JSONObject o = new JSONObject();
o.put("deviceHandle", mHandle);
o.put("state", newState);
keepCallback(mConnectContext, o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
} else {
mConnectContext.error(status);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt g, int rssi, int status)
{
CallbackContext c = mRssiContext;
mRssiContext = null;
if(status == BluetoothGatt.GATT_SUCCESS) {
c.success(rssi);
} else {
c.error(status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt g, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = g.getServices();
JSONArray a = new JSONArray();
for(BluetoothGattService s : services) {
// give the service a handle.
if(mServices == null)
mServices = new HashMap<Integer, BluetoothGattService>();
Object res = mServices.put(mNextHandle, s);
assert(res == null);
try {
JSONObject o = new JSONObject();
o.put("handle", mNextHandle);
o.put("uuid", s.getUuid().toString());
o.put("type", s.getType());
mNextHandle++;
a.put(o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
}
mCurrentOpContext.success(a);
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicRead(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(c.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorRead(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(d.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicWrite(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorWrite(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
// We write the notification config descriptor in native code,
// and in this case there is no callback context. Thus we check
// if the context is null here.
// TODO: Encapsulate exposed instance variables in this file,
// use method calls instead.
if (mCurrentOpContext != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
}
mCurrentOp = false;
process();
}
@Override
public void onCharacteristicChanged(BluetoothGatt g, BluetoothGattCharacteristic c)
{
CallbackContext cc = mNotifications.get(c);
keepCallback(cc, c.getValue());
}
}
// ************* BLE PERIPHERAL ROLE *************
// Implementation of advertisement API.
private BluetoothLeAdvertiser mAdvertiser;
private AdvertiseCallback mAdCallback;
private AdvertiseSettings buildAdvertiseSettings(JSONObject setJson) throws JSONException
{
AdvertiseSettings.Builder setBuild = new AdvertiseSettings.Builder();
{
String advModeString = setJson.optString("advertiseMode", "ADVERTISE_MODE_LOW_POWER");
int advMode;
if(advModeString.equals("ADVERTISE_MODE_LOW_POWER"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
else if(advModeString.equals("ADVERTISE_MODE_BALANCED"))
advMode = AdvertiseSettings.ADVERTISE_MODE_BALANCED;
else if(advModeString.equals("ADVERTISE_MODE_LOW_LATENCY"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY;
else
throw new JSONException("Invalid advertiseMode: "+advModeString);
setBuild.setAdvertiseMode(advMode);
}
boolean connectable = setJson.optBoolean("connectable", mGattServer != null);
System.out.println("connectable: "+connectable);
setBuild.setConnectable(connectable);
setBuild.setTimeout(setJson.optInt("timeoutMillis", 0));
{
String advModeString = setJson.optString("txPowerLevel", "ADVERTISE_TX_POWER_MEDIUM");
int advMode;
if(advModeString.equals("ADVERTISE_TX_POWER_ULTRA_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_MEDIUM"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM;
else if(advModeString.equals("ADVERTISE_TX_POWER_HIGH"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_HIGH;
else
throw new JSONException("Invalid txPowerLevel");
setBuild.setTxPowerLevel(advMode);
}
return setBuild.build();
}
private AdvertiseData buildAdvertiseData(JSONObject dataJson) throws JSONException
{
if(dataJson == null)
return null;
AdvertiseData.Builder dataBuild = new AdvertiseData.Builder();
dataBuild.setIncludeDeviceName(dataJson.optBoolean("includeDeviceName", false));
dataBuild.setIncludeTxPowerLevel(dataJson.optBoolean("includeTxPowerLevel", false));
JSONArray serviceUUIDs = dataJson.optJSONArray("serviceUUIDs");
if(serviceUUIDs != null) {
for(int i=0; i<serviceUUIDs.length(); i++) {
dataBuild.addServiceUuid(new ParcelUuid(UUID.fromString(serviceUUIDs.getString(i))));
}
}
JSONObject serviceData = dataJson.optJSONObject("serviceData");
if(serviceData != null) {
Iterator<String> keys = serviceData.keys();
while(keys.hasNext()) {
String key = keys.next();
ParcelUuid uuid = new ParcelUuid(UUID.fromString(key));
byte[] data = Base64.decode(serviceData.getString(key), Base64.DEFAULT);
dataBuild.addServiceData(uuid, data);
}
}
JSONObject manufacturerData = dataJson.optJSONObject("manufacturerData");
if(manufacturerData != null) {
Iterator<String> keys = manufacturerData.keys();
while(keys.hasNext()) {
String key = keys.next();
int id = Integer.parseInt(key);
byte[] data = Base64.decode(manufacturerData.getString(key), Base64.DEFAULT);
dataBuild.addManufacturerData(id, data);
}
}
return dataBuild.build();
}
private void startAdvertise(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mAdCallback != null) {
cc.error("Advertise must be stopped first!");
return;
}
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isMultipleAdvertisementSupported()) {
cc.error("BLE advertisement not supported by this device!");
return;
}
JSONObject setJson = args.getJSONObject(0);
// build settings. this checks arguments for validity.
final AdvertiseSettings settings = buildAdvertiseSettings(setJson);
// build data. this checks arguments for validity.
final AdvertiseData broadcastData = buildAdvertiseData(setJson.getJSONObject("broadcastData"));
final AdvertiseData scanResponseData = buildAdvertiseData(setJson.optJSONObject("scanResponseData"));
mAdCallback = new AdvertiseCallback()
{
@Override
public void onStartFailure(int errorCode)
{
mAdCallback = null;
// translate available error codes using reflection.
// we're looking for all fields typed "public static final int".
Field[] fields = AdvertiseCallback.class.getDeclaredFields();
String errorMessage = null;
for(int i=0; i<fields.length; i++) {
Field f = fields[i];
System.out.println("Field: Class "+f.getType().getName()+". Modifiers: "+Modifier.toString(f.getModifiers()));
if(f.getType() == int.class &&
f.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))
{
try {
if(f.getInt(null) == errorCode) {
errorMessage = f.getName();
break;
}
} catch(IllegalAccessException e) {
// if this happens, it is an internal error.
e.printStackTrace();
}
}
}
if(errorMessage == null) {
errorMessage = Integer.toString(errorCode);
}
cc.error("AdvertiseCallback.onStartFailure: "+errorMessage);
}
public void onStartSuccess(AdvertiseSettings settingsInEffect)
{
cc.success();
}
};
// ensure Bluetooth is powered on, then start advertising.
checkPowerState(adapter, cc, new Runnable()
{
@Override
public void run()
{
try {
mAdvertiser = adapter.getBluetoothLeAdvertiser();
if(scanResponseData != null) {
mAdvertiser.startAdvertising(settings, broadcastData, scanResponseData, mAdCallback);
} else {
mAdvertiser.startAdvertising(settings, broadcastData, mAdCallback);
}
} catch(Exception e) {
mAdCallback = null;
e.printStackTrace();
cc.error(e.toString());
}
}
});
}
private void stopAdvertise(final CordovaArgs args, final CallbackContext cc)
{
if(mAdvertiser != null && mAdCallback != null) {
mAdvertiser.stopAdvertising(mAdCallback);
mAdCallback = null;
}
cc.success();
}
private BluetoothGattServer mGattServer;
private MyBluetoothGattServerCallback mGattServerCallback;
private void startGattServer(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer != null) {
cc.error("GATT server already started!");
return;
}
JSONObject settings = args.getJSONObject(0);
mGattServerCallback = new MyBluetoothGattServerCallback(settings.getInt("nextHandle"), cc);
mGattServer = ((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE))
.openGattServer(mContext, mGattServerCallback);
JSONArray services = settings.getJSONArray("services");
for(int i=0; i<services.length(); i++) {
JSONObject service = services.getJSONObject(i);
BluetoothGattService s = new BluetoothGattService(
UUID.fromString(service.getString("uuid")), service.getInt("type"));
JSONArray characteristics = service.optJSONArray("characteristics");
if(characteristics != null) {
for(int j=0; j<characteristics.length(); j++) {
JSONObject characteristic = characteristics.getJSONObject(j);
System.out.println("characteristic:"+characteristic.toString(1));
BluetoothGattCharacteristic c = new BluetoothGattCharacteristic(
UUID.fromString(characteristic.getString("uuid")),
characteristic.getInt("properties"), characteristic.getInt("permissions"));
mGattServerCallback.mReadHandles.put(c, characteristic.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(c, characteristic.getInt("onWriteRequestHandle"));
JSONArray descriptors = characteristic.optJSONArray("descriptors");
if(descriptors != null) for(int k=0; k<descriptors.length(); k++) {
JSONObject descriptor = descriptors.getJSONObject(k);
System.out.println("descriptor:"+descriptor.toString(1));
BluetoothGattDescriptor d = new BluetoothGattDescriptor(
UUID.fromString(descriptor.getString("uuid")),
descriptor.getInt("permissions"));
c.addDescriptor(d);
mGattServerCallback.mReadHandles.put(d, descriptor.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(d, descriptor.getInt("onWriteRequestHandle"));
}
s.addCharacteristic(c);
}
}
mGattServer.addService(s);
}
keepCallback(cc, new JSONObject().put("name", "win"));
}
private void stopGattServer(final CordovaArgs args, final CallbackContext cc)
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
mGattServer.close();
mGattServer = null;
cc.success();
}
class MyBluetoothGattServerCallback extends BluetoothGattServerCallback
{
// Bidirectional maps; look up object from handle, or handle from object.
// The JavaScript side needs handles, the native side needs objects.
public HashMap<Integer, BluetoothDevice> mDevices;
public HashMap<Object, Integer> mDeviceHandles;
public HashMap<Object, Integer> mReadHandles;
public HashMap<Object, Integer> mWriteHandles;
int mNextHandle;
CallbackContext mCC;
CallbackContext mNotifyCC;
MyBluetoothGattServerCallback(int nextHandle, final CallbackContext cc)
{
mNextHandle = nextHandle;
mDevices = new HashMap<Integer, BluetoothDevice>();
mDeviceHandles = new HashMap<Object, Integer>();
mReadHandles = new HashMap<Object, Integer>();
mWriteHandles = new HashMap<Object, Integer>();
mCC = cc;
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState)
{
System.out.println("onConnectionStateChange("+device.getAddress()+", "+status+", "+newState+")");
Integer handle = mDeviceHandles.get(device);
if(handle == null) {
handle = new Integer(mNextHandle++);
mDeviceHandles.put(device, handle);
mDevices.put(handle, device);
}
try {
keepCallback(mCC, new JSONObject()
.put("name", "connection")
.put("deviceHandle", handle)
.put("connected", newState == BluetoothProfile.STATE_CONNECTED)
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattCharacteristic characteristic)
{
System.out.println("onCharacteristicReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattDescriptor descriptor)
{
System.out.println("onDescriptorReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattCharacteristic characteristic,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onCharacteristicWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattDescriptor descriptor,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onDescriptorWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute)
{
System.out.println("onExecuteWrite("+device.getAddress()+", "+requestId+", "+execute+")");
mGattServer.sendResponse(device, requestId, 0, 0, null);
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu)
{
System.out.println("onMtuChanged("+mtu+")");
}
@Override
public void onNotificationSent(BluetoothDevice device, int status)
{
System.out.println("onNotificationSent("+device.getAddress()+", "+status+")");
if(status == BluetoothGatt.GATT_SUCCESS)
mNotifyCC.success();
else
mNotifyCC.error(status);
mNotifyCC = null;
}
@Override
public void onServiceAdded(int status, BluetoothGattService service)
{
System.out.println("onServiceAdded("+status+")");
}
}
private void sendResponse(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
int deviceHandle = args.getInt(0);
int requestId = args.getInt(1);
byte[] data = args.getArrayBuffer(2);
boolean res = mGattServer.sendResponse(
mGattServerCallback.mDevices.get(deviceHandle),
requestId,
0,
0,
data);
System.out.println("sendResponse result: "+res);
cc.success();
}
private void notify(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
}
}
| src/android/BLE.java | /*
Copyright 2014 Evothings AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.evothings;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.*;
import android.bluetooth.le.*;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.*;
import android.app.Activity;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.*;
import android.util.Base64;
import android.os.ParcelUuid;
import android.util.Log;
import android.content.pm.PackageManager;
import android.os.Build;
import android.Manifest;
public class BLE
extends CordovaPlugin
implements
LeScanCallback
{
// ************* BLE CENTRAL ROLE *************
// Implementation of BLE Central API.
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
// Used by startScan().
private CallbackContext mScanCallbackContext;
private CordovaArgs mScanArgs;
// Used by reset().
private CallbackContext mResetCallbackContext;
// The Android application Context.
private Context mContext;
private boolean mRegisteredReceiver = false;
// Called when the device's Bluetooth powers on.
// Used by startScan() and connect() to wait for power-on if Bluetooth was
// off when the function was called.
private Runnable mOnPowerOn;
// Used to send error messages to the JavaScript side if Bluetooth power-on fails.
private CallbackContext mPowerOnCallbackContext;
// Map of connected devices.
HashMap<Integer, GattHandler> mConnectedDevices = null;
// Monotonically incrementing key to the Gatt map.
int mNextGattHandle = 1;
// Called each time cordova.js is loaded.
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
mContext = webView.getContext();
if(!mRegisteredReceiver) {
mContext.registerReceiver(
new BluetoothStateReceiver(),
new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
mRegisteredReceiver = true;
}
}
// Handles JavaScript-to-native function calls.
// Returns true if a supported function was called, false otherwise.
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
{
try {
if("startScan".equals(action)) { startScan(args, callbackContext); return true; }
else if("stopScan".equals(action)) { stopScan(args, callbackContext); return true; }
else if("connect".equals(action)) { connect(args, callbackContext); return true; }
else if("close".equals(action)) { close(args, callbackContext); return true; }
else if("rssi".equals(action)) { rssi(args, callbackContext); return true; }
else if("services".equals(action)) { services(args, callbackContext); return true; }
else if("characteristics".equals(action)) { characteristics(args, callbackContext); return true; }
else if("descriptors".equals(action)) { descriptors(args, callbackContext); return true; }
else if("readCharacteristic".equals(action)) { readCharacteristic(args, callbackContext); return true; }
else if("readDescriptor".equals(action)) { readDescriptor(args, callbackContext); return true; }
else if("writeCharacteristic".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); return true; }
else if("writeCharacteristicWithoutResponse".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); return true; }
else if("writeDescriptor".equals(action)) { writeDescriptor(args, callbackContext); return true; }
else if("enableNotification".equals(action)) { enableNotification(args, callbackContext); return true; }
else if("disableNotification".equals(action)) { disableNotification(args, callbackContext); return true; }
else if("testCharConversion".equals(action)) { testCharConversion(args, callbackContext); return true; }
else if("reset".equals(action)) { reset(args, callbackContext); return true; }
else if("startAdvertise".equals(action)) { startAdvertise(args, callbackContext); return true; }
else if("stopAdvertise".equals(action)) { stopAdvertise(args, callbackContext); return true; }
else if("startGattServer".equals(action)) { startGattServer(args, callbackContext); return true; }
else if("stopGattServer".equals(action)) { stopGattServer(args, callbackContext); return true; }
else if("sendResponse".equals(action)) { sendResponse(args, callbackContext); return true; }
else if("notify".equals(action)) { notify(args, callbackContext); return true; }
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
}
return false;
}
/**
* Called when the WebView does a top-level navigation or refreshes.
*
* Plugins should stop any long-running processes and clean up internal state.
*
* Does nothing by default.
*
* Our version should stop any ongoing scan, and close any existing connections.
*/
@Override
public void onReset()
{
if(mScanCallbackContext != null) {
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
a.stopLeScan(this);
mScanCallbackContext = null;
}
if(mConnectedDevices != null) {
Iterator<GattHandler> itr = mConnectedDevices.values().iterator();
while(itr.hasNext()) {
GattHandler gh = itr.next();
if(gh.mGatt != null)
gh.mGatt.close();
}
mConnectedDevices.clear();
}
if(mGattServer != null) {
mGattServer.close();
mGattServer = null;
}
}
// Possibly asynchronous.
// Ensures Bluetooth is powered on, then calls the Runnable \a onPowerOn.
// Calls cc.error if power-on fails.
private void checkPowerState(BluetoothAdapter adapter, CallbackContext cc, Runnable onPowerOn)
{
if(adapter == null) {
cc.error("Bluetooth not supported");
return;
}
if(adapter.getState() == BluetoothAdapter.STATE_ON) {
// Bluetooth is ON
onPowerOn.run();
} else {
mOnPowerOn = onPowerOn;
mPowerOnCallbackContext = cc;
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
cordova.startActivityForResult(this, enableBtIntent, 0);
}
}
// Called whe the Bluetooth power-on request is completed.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Runnable onPowerOn = mOnPowerOn;
CallbackContext cc = mPowerOnCallbackContext;
mOnPowerOn = null;
mPowerOnCallbackContext = null;
if(resultCode == Activity.RESULT_OK) {
if (null != onPowerOn) {
onPowerOn.run();
} else {
// Runnable was null.
if (null != cc) cc.error("Runnable is null in onActivityResult (internal error)");
}
} else {
if(resultCode == Activity.RESULT_CANCELED) {
if (null != cc) cc.error("Bluetooth power-on canceled");
} else {
if (null != cc) cc.error("Bluetooth power-on failed with code: "+resultCode);
}
}
}
// These three functions each send a JavaScript callback *without* removing
// the callback context, as is default.
private void keepCallback(final CallbackContext callbackContext, JSONObject message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, String message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, byte[] message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
// Callback from cordova.requestPermissions().
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
//Log.i("@@@@@@@@", "onRequestPermissionsResult: " + permissions + " " + grantResults);
if (PERMISSION_REQUEST_COARSE_LOCATION == requestCode)
{
if (PackageManager.PERMISSION_GRANTED == grantResults[0])
{
//Log.i("@@@@@@@@", "Coarse location permission granted");
// Permission ok, start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
else
{
//Log.i("@@@@@@@@", "Coarse location permission NOT granted");
// Permission NOT ok, send callback error.
mScanCallbackContext.error("Location permission not granted");
mScanCallbackContext = null;
}
}
}
// API implementation. See ble.js for documentation.
private void startScan(final CordovaArgs args, final CallbackContext callbackContext)
{
// Save callback context.
mScanCallbackContext = callbackContext;
mScanArgs = args;
// Cordova Permission check
if (!cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
{
//Log.i("@@@@@@@@", "PERMISSION NEEDED");
// Permission needed. Ask user.
cordova.requestPermission(this, PERMISSION_REQUEST_COARSE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION);
return;
}
// Permission ok, go ahead and start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
private void startScanImpl(final CordovaArgs args, final CallbackContext callbackContext)
{
//Log.i("@@@@@@", "Start scan");
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final LeScanCallback self = this;
// Get service UUIDs.
UUID[] uuidArray = null;
try
{
JSONArray uuids = args.getJSONArray(0);
if (null != uuids)
{
uuidArray = new UUID[uuids.length()];
for (int i = 0; i < uuids.length(); ++i)
{
uuidArray[i] = UUID.fromString(uuids.getString(i));
}
}
}
catch(JSONException ex)
{
uuidArray = null;
}
final UUID[] serviceUUIDs = uuidArray;
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
if(!adapter.startLeScan(serviceUUIDs, self))
{
//Log.i("@@@@@@", "Start scan failed");
callbackContext.error("Android function startLeScan failed");
mScanCallbackContext = null;
return;
}
}
});
}
// Called during scan, when a device advertisement is received.
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
//Log.i("@@@@@@", "onLeScan");
if (mScanCallbackContext == null)
{
return;
}
try
{
//Log.i("@@@@@@", "onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
//System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("address", device.getAddress());
jsonObject.put("rssi", rssi);
jsonObject.put("name", device.getName());
jsonObject.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
keepCallback(mScanCallbackContext, jsonObject);
}
catch(JSONException e)
{
mScanCallbackContext.error(e.toString());
}
}
// API implementation.
private void stopScan(final CordovaArgs args, final CallbackContext callbackContext)
{
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.stopLeScan(this);
mScanCallbackContext = null;
}
// API implementation.
private void connect(final CordovaArgs args, final CallbackContext callbackContext)
{
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
try {
// Each device connection has a GattHandler, which handles the events the can happen to the connection.
// The implementation of the GattHandler class is found at the end of this file.
GattHandler gh = new GattHandler(mNextGattHandle, callbackContext);
gh.mGatt = adapter.getRemoteDevice(args.getString(0)).connectGatt(mContext, true, gh);
// Note that gh.mGatt and this.mGatt are different object and have different types.
// --> Renamed this.mGatt to mConnectedDevices to avoid confusion.
if(mConnectedDevices == null)
mConnectedDevices = new HashMap<Integer, GattHandler>();
Object res = mConnectedDevices.put(mNextGattHandle, gh);
assert(res == null);
mNextGattHandle++;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
});
}
// API implementation.
private void close(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mGatt.close();
mConnectedDevices.remove(args.getInt(0));
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void rssi(final CordovaArgs args, final CallbackContext callbackContext)
{
GattHandler gh = null;
try {
gh = mConnectedDevices.get(args.getInt(0));
if(gh.mRssiContext != null) {
callbackContext.error("Previous call to rssi() not yet completed!");
return;
}
gh.mRssiContext = callbackContext;
if(!gh.mGatt.readRemoteRssi()) {
gh.mRssiContext = null;
callbackContext.error("readRemoteRssi");
}
} catch(Exception e) {
e.printStackTrace();
if(gh != null) {
gh.mRssiContext = null;
}
callbackContext.error(e.toString());
}
}
// API implementation.
private void services(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.discoverServices()) {
gh.mCurrentOpContext = null;
callbackContext.error("discoverServices");
gh.process();
}
}
});
gh.process();
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void characteristics(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattCharacteristic c : gh.mServices.get(args.getInt(1)).getCharacteristics()) {
if(gh.mCharacteristics == null)
gh.mCharacteristics = new HashMap<Integer, BluetoothGattCharacteristic>();
Object res = gh.mCharacteristics.put(gh.mNextHandle, c);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", c.getUuid().toString());
o.put("permissions", c.getPermissions());
o.put("properties", c.getProperties());
o.put("writeType", c.getWriteType());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void descriptors(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattDescriptor d : gh.mCharacteristics.get(args.getInt(1)).getDescriptors()) {
if(gh.mDescriptors == null)
gh.mDescriptors = new HashMap<Integer, BluetoothGattDescriptor>();
Object res = gh.mDescriptors.put(gh.mNextHandle, d);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", d.getUuid().toString());
o.put("permissions", d.getPermissions());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void readCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readCharacteristic(gh.mCharacteristics.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void readDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readDescriptor(gh.mDescriptors.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext,
final int writeType)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattCharacteristic c = gh.mCharacteristics.get(args.getInt(1));
System.out.println("writeCharacteristic("+args.getInt(0)+", "+args.getInt(1)+", "+args.getString(2)+")");
c.setWriteType(writeType);
c.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeCharacteristic(c)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattDescriptor d = gh.mDescriptors.get(args.getInt(1));
d.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeDescriptor(d)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// Notification options flag.
private final int NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG = 1;
// API implementation.
private void enableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification on.
boolean setConfigDescriptor =
NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
(NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
turnNotificationOn(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// API implementation.
private void disableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification off.
boolean setConfigDescriptor =
NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
(NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
turnNotificationOff(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// Helper method.
private void turnNotificationOn(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
if (setConfigDescriptor) {
// Write the config descriptor and enable notification.
if (enableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Enable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when enabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean enableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Config descriptor value.
byte[] descriptorValue;
// Check if notification or indication should be used.
if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
}
else if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
}
else {
callbackContext.error("Characteristic does not support notification or indication.");
gattHandler.process();
return false;
}
// Set value of config descriptor.
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void enableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification on.
boolean success = gatt.setCharacteristicNotification(characteristic, true);
if (!success) {
callbackContext.error("Could not enable notification");
gattHandler.process();
return;
}
// Save callback context for the characteristic.
// When turning notification on, the success callback will be
// called on every notification event.
gattHandler.mNotifications.put(characteristic, callbackContext);
}
// Helper method.
private void turnNotificationOff(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
// Remove callback context for the characteristic
// when turning off notification.
gattHandler.mNotifications.remove(characteristic);
if (setConfigDescriptor) {
// Write the config descriptor and disable notification.
if (disableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Disable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when disabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean disableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Set value of config descriptor.
byte[] descriptorValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void disableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification off.
boolean success = gatt.setCharacteristicNotification(characteristic, false);
if (!success) {
callbackContext.error("Could not disable notification");
gattHandler.process();
return;
}
// Call success callback when notification is turned off.
callbackContext.success();
}
// API implementation.
private void testCharConversion(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
byte[] b = {(byte)args.getInt(0)};
callbackContext.success(b);
}
// API implementation.
private void reset(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
mResetCallbackContext = null;
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
if(mScanCallbackContext != null) {
a.stopLeScan(this);
mScanCallbackContext = null;
}
int state = a.getState();
//STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF.
if(state == BluetoothAdapter.STATE_TURNING_ON) {
// reset in progress; wait for STATE_ON.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_TURNING_OFF) {
// reset in progress; wait for STATE_OFF.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("enable");
}
return;
}
if(state == BluetoothAdapter.STATE_ON) {
boolean res = a.disable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("disable");
}
return;
}
cc.error("Unknown state: "+state);
}
// Receives notification about Bluetooth power on and off. Used by reset().
class BluetoothStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
int state = a.getState();
System.out.println("BluetoothState: "+a);
if(mResetCallbackContext != null) {
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(!res) {
mResetCallbackContext.error("enable");
mResetCallbackContext = null;
}
}
if(state == BluetoothAdapter.STATE_ON) {
mResetCallbackContext.success();
mResetCallbackContext = null;
}
}
}
};
/* Running more than one operation of certain types on remote Gatt devices
* seem to cause it to stop responding.
* The known types are 'read' and 'write'.
* I've added 'services' to be on the safe side.
* 'rssi' and 'notification' should be safe.
*/
// This class handles callbacks pertaining to device connections.
// Also maintains the per-device operation queue.
private class GattHandler extends BluetoothGattCallback
{
// Local copy of the key to BLE.mGatt. Fed by BLE.mNextGattHandle.
final int mHandle;
// The queue of operations.
LinkedList<Runnable> mOperations = new LinkedList<Runnable>();
// connect() and rssi() are handled separately from other operations.
CallbackContext mConnectContext;
CallbackContext mRssiContext;
CallbackContext mCurrentOpContext;
// Special flag for doing async operations without a Cordova callback context.
// Used when writing notification config descriptor.
boolean mCurrentOp = false;
// The Android API connection.
BluetoothGatt mGatt;
// Maps of integer to Gatt subobject.
HashMap<Integer, BluetoothGattService> mServices;
HashMap<Integer, BluetoothGattCharacteristic> mCharacteristics;
HashMap<Integer, BluetoothGattDescriptor> mDescriptors;
// Monotonically incrementing key to the subobject maps.
int mNextHandle = 1;
// Notification callbacks. The BluetoothGattCharacteristic object, as found
// in the mCharacteristics map, is the key.
HashMap<BluetoothGattCharacteristic, CallbackContext> mNotifications =
new HashMap<BluetoothGattCharacteristic, CallbackContext>();
GattHandler(int h, CallbackContext cc)
{
mHandle = h;
mConnectContext = cc;
}
// Run the next operation, if any.
void process()
{
if(mCurrentOpContext != null || mCurrentOp)
return;
Runnable r = mOperations.poll();
if(r == null)
return;
r.run();
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
try {
JSONObject o = new JSONObject();
o.put("deviceHandle", mHandle);
o.put("state", newState);
keepCallback(mConnectContext, o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
} else {
mConnectContext.error(status);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt g, int rssi, int status)
{
CallbackContext c = mRssiContext;
mRssiContext = null;
if(status == BluetoothGatt.GATT_SUCCESS) {
c.success(rssi);
} else {
c.error(status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt g, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = g.getServices();
JSONArray a = new JSONArray();
for(BluetoothGattService s : services) {
// give the service a handle.
if(mServices == null)
mServices = new HashMap<Integer, BluetoothGattService>();
Object res = mServices.put(mNextHandle, s);
assert(res == null);
try {
JSONObject o = new JSONObject();
o.put("handle", mNextHandle);
o.put("uuid", s.getUuid().toString());
o.put("type", s.getType());
mNextHandle++;
a.put(o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
}
mCurrentOpContext.success(a);
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicRead(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(c.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorRead(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(d.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicWrite(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorWrite(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
// We write the notification config descriptor in native code,
// and in this case there is no callback context. Thus we check
// if the context is null here.
// TODO: Encapsulate exposed instance variables in this file,
// use method calls instead.
if (mCurrentOpContext != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
}
mCurrentOp = false;
process();
}
@Override
public void onCharacteristicChanged(BluetoothGatt g, BluetoothGattCharacteristic c)
{
CallbackContext cc = mNotifications.get(c);
keepCallback(cc, c.getValue());
}
}
// ************* BLE PERIPHERAL ROLE *************
// Implementation of advertisement API.
private BluetoothLeAdvertiser mAdvertiser;
private AdvertiseCallback mAdCallback;
private AdvertiseSettings buildAdvertiseSettings(JSONObject setJson) throws JSONException
{
AdvertiseSettings.Builder setBuild = new AdvertiseSettings.Builder();
{
String advModeString = setJson.optString("advertiseMode", "ADVERTISE_MODE_LOW_POWER");
int advMode;
if(advModeString.equals("ADVERTISE_MODE_LOW_POWER"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
else if(advModeString.equals("ADVERTISE_MODE_BALANCED"))
advMode = AdvertiseSettings.ADVERTISE_MODE_BALANCED;
else if(advModeString.equals("ADVERTISE_MODE_LOW_LATENCY"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY;
else
throw new JSONException("Invalid advertiseMode: "+advModeString);
setBuild.setAdvertiseMode(advMode);
}
boolean connectable = setJson.optBoolean("connectable", mGattServer != null);
System.out.println("connectable: "+connectable);
setBuild.setConnectable(connectable);
setBuild.setTimeout(setJson.optInt("timeoutMillis", 0));
{
String advModeString = setJson.optString("txPowerLevel", "ADVERTISE_TX_POWER_MEDIUM");
int advMode;
if(advModeString.equals("ADVERTISE_TX_POWER_ULTRA_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_MEDIUM"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM;
else if(advModeString.equals("ADVERTISE_TX_POWER_HIGH"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_HIGH;
else
throw new JSONException("Invalid txPowerLevel");
setBuild.setTxPowerLevel(advMode);
}
return setBuild.build();
}
private AdvertiseData buildAdvertiseData(JSONObject dataJson) throws JSONException
{
if(dataJson == null)
return null;
AdvertiseData.Builder dataBuild = new AdvertiseData.Builder();
dataBuild.setIncludeDeviceName(dataJson.optBoolean("includeDeviceName", false));
dataBuild.setIncludeTxPowerLevel(dataJson.optBoolean("includeTxPowerLevel", false));
JSONArray serviceUUIDs = dataJson.optJSONArray("serviceUUIDs");
if(serviceUUIDs != null) {
for(int i=0; i<serviceUUIDs.length(); i++) {
dataBuild.addServiceUuid(new ParcelUuid(UUID.fromString(serviceUUIDs.getString(i))));
}
}
JSONObject serviceData = dataJson.optJSONObject("serviceData");
if(serviceData != null) {
Iterator<String> keys = serviceData.keys();
while(keys.hasNext()) {
String key = keys.next();
ParcelUuid uuid = new ParcelUuid(UUID.fromString(key));
byte[] data = Base64.decode(serviceData.getString(key), Base64.DEFAULT);
dataBuild.addServiceData(uuid, data);
}
}
JSONObject manufacturerData = dataJson.optJSONObject("manufacturerData");
if(manufacturerData != null) {
Iterator<String> keys = manufacturerData.keys();
while(keys.hasNext()) {
String key = keys.next();
int id = Integer.parseInt(key);
byte[] data = Base64.decode(manufacturerData.getString(key), Base64.DEFAULT);
dataBuild.addManufacturerData(id, data);
}
}
return dataBuild.build();
}
private void startAdvertise(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mAdCallback != null) {
cc.error("Advertise must be stopped first!");
return;
}
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isMultipleAdvertisementSupported()) {
cc.error("BLE advertisement not supported by this device!");
return;
}
JSONObject setJson = args.getJSONObject(0);
// build settings. this checks arguments for validity.
final AdvertiseSettings settings = buildAdvertiseSettings(setJson);
// build data. this checks arguments for validity.
final AdvertiseData broadcastData = buildAdvertiseData(setJson.getJSONObject("broadcastData"));
final AdvertiseData scanResponseData = buildAdvertiseData(setJson.optJSONObject("scanResponseData"));
mAdCallback = new AdvertiseCallback()
{
@Override
public void onStartFailure(int errorCode)
{
mAdCallback = null;
// translate available error codes using reflection.
// we're looking for all fields typed "public static final int".
Field[] fields = AdvertiseCallback.class.getDeclaredFields();
String errorMessage = null;
for(int i=0; i<fields.length; i++) {
Field f = fields[i];
System.out.println("Field: Class "+f.getType().getName()+". Modifiers: "+Modifier.toString(f.getModifiers()));
if(f.getType() == int.class &&
f.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))
{
try {
if(f.getInt(null) == errorCode) {
errorMessage = f.getName();
break;
}
} catch(IllegalAccessException e) {
// if this happens, it is an internal error.
e.printStackTrace();
}
}
}
if(errorMessage == null) {
errorMessage = Integer.toString(errorCode);
}
cc.error("AdvertiseCallback.onStartFailure: "+errorMessage);
}
public void onStartSuccess(AdvertiseSettings settingsInEffect)
{
cc.success();
}
};
// ensure Bluetooth is powered on, then start advertising.
checkPowerState(adapter, cc, new Runnable()
{
@Override
public void run()
{
try {
mAdvertiser = adapter.getBluetoothLeAdvertiser();
if(scanResponseData != null) {
mAdvertiser.startAdvertising(settings, broadcastData, scanResponseData, mAdCallback);
} else {
mAdvertiser.startAdvertising(settings, broadcastData, mAdCallback);
}
} catch(Exception e) {
mAdCallback = null;
e.printStackTrace();
cc.error(e.toString());
}
}
});
}
private void stopAdvertise(final CordovaArgs args, final CallbackContext cc)
{
if(mAdvertiser != null && mAdCallback != null) {
mAdvertiser.stopAdvertising(mAdCallback);
mAdCallback = null;
}
cc.success();
}
private BluetoothGattServer mGattServer;
private MyBluetoothGattServerCallback mGattServerCallback;
private void startGattServer(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer != null) {
cc.error("GATT server already started!");
return;
}
JSONObject settings = args.getJSONObject(0);
mGattServerCallback = new MyBluetoothGattServerCallback(settings.getInt("nextHandle"), cc);
mGattServer = ((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE))
.openGattServer(mContext, mGattServerCallback);
JSONArray services = settings.getJSONArray("services");
for(int i=0; i<services.length(); i++) {
JSONObject service = services.getJSONObject(i);
BluetoothGattService s = new BluetoothGattService(
UUID.fromString(service.getString("uuid")), service.getInt("type"));
JSONArray characteristics = service.optJSONArray("characteristics");
if(characteristics != null) {
for(int j=0; j<characteristics.length(); j++) {
JSONObject characteristic = characteristics.getJSONObject(j);
System.out.println("characteristic:"+characteristic.toString(1));
BluetoothGattCharacteristic c = new BluetoothGattCharacteristic(
UUID.fromString(characteristic.getString("uuid")),
characteristic.getInt("properties"), characteristic.getInt("permissions"));
mGattServerCallback.mReadHandles.put(c, characteristic.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(c, characteristic.getInt("onWriteRequestHandle"));
JSONArray descriptors = characteristic.optJSONArray("descriptors");
if(descriptors != null) for(int k=0; k<descriptors.length(); k++) {
JSONObject descriptor = descriptors.getJSONObject(k);
System.out.println("descriptor:"+descriptor.toString(1));
BluetoothGattDescriptor d = new BluetoothGattDescriptor(
UUID.fromString(descriptor.getString("uuid")),
descriptor.getInt("permissions"));
c.addDescriptor(d);
mGattServerCallback.mReadHandles.put(d, descriptor.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(d, descriptor.getInt("onWriteRequestHandle"));
}
s.addCharacteristic(c);
}
}
mGattServer.addService(s);
}
keepCallback(cc, new JSONObject().put("name", "win"));
}
private void stopGattServer(final CordovaArgs args, final CallbackContext cc)
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
mGattServer.close();
mGattServer = null;
cc.success();
}
class MyBluetoothGattServerCallback extends BluetoothGattServerCallback
{
// Bidirectional maps; look up object from handle, or handle from object.
// The JavaScript side needs handles, the native side needs objects.
public HashMap<Integer, BluetoothDevice> mDevices;
public HashMap<Object, Integer> mDeviceHandles;
public HashMap<Object, Integer> mReadHandles;
public HashMap<Object, Integer> mWriteHandles;
int mNextHandle;
CallbackContext mCC;
CallbackContext mNotifyCC;
MyBluetoothGattServerCallback(int nextHandle, final CallbackContext cc)
{
mNextHandle = nextHandle;
mDevices = new HashMap<Integer, BluetoothDevice>();
mDeviceHandles = new HashMap<Object, Integer>();
mReadHandles = new HashMap<Object, Integer>();
mWriteHandles = new HashMap<Object, Integer>();
mCC = cc;
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState)
{
System.out.println("onConnectionStateChange("+device.getAddress()+", "+status+", "+newState+")");
Integer handle = mDeviceHandles.get(device);
if(handle == null) {
handle = new Integer(mNextHandle++);
mDeviceHandles.put(device, handle);
mDevices.put(handle, device);
}
try {
keepCallback(mCC, new JSONObject()
.put("name", "connection")
.put("deviceHandle", handle)
.put("connected", newState == BluetoothProfile.STATE_CONNECTED)
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattCharacteristic characteristic)
{
System.out.println("onCharacteristicReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattDescriptor descriptor)
{
System.out.println("onDescriptorReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattCharacteristic characteristic,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onCharacteristicWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattDescriptor descriptor,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onDescriptorWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute)
{
System.out.println("onExecuteWrite("+device.getAddress()+", "+requestId+", "+execute+")");
mGattServer.sendResponse(device, requestId, 0, 0, null);
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu)
{
System.out.println("onMtuChanged("+mtu+")");
}
@Override
public void onNotificationSent(BluetoothDevice device, int status)
{
System.out.println("onNotificationSent("+device.getAddress()+", "+status+")");
if(status == BluetoothGatt.GATT_SUCCESS)
mNotifyCC.success();
else
mNotifyCC.error(status);
mNotifyCC = null;
}
@Override
public void onServiceAdded(int status, BluetoothGattService service)
{
System.out.println("onServiceAdded("+status+")");
}
}
private void sendResponse(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
int deviceHandle = args.getInt(0);
int requestId = args.getInt(1);
byte[] data = args.getArrayBuffer(2);
boolean res = mGattServer.sendResponse(
mGattServerCallback.mDevices.get(deviceHandle),
requestId,
0,
0,
data);
System.out.println("sendResponse result: "+res);
cc.success();
}
private void notify(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
}
}
| Fixed bug that made notifications not being automatically enabled.
| src/android/BLE.java | Fixed bug that made notifications not being automatically enabled. | <ide><path>rc/android/BLE.java
<ide> int options = args.getInt(2);
<ide>
<ide> // Turn notification on.
<del> boolean setConfigDescriptor =
<del> NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
<del> (NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
<add> boolean setConfigDescriptor = (options == 0);
<ide> turnNotificationOn(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
<ide> }
<ide>
<ide> int options = args.getInt(2);
<ide>
<ide> // Turn notification off.
<del> boolean setConfigDescriptor =
<del> NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
<del> (NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
<add> boolean setConfigDescriptor = (options == 0);
<ide> turnNotificationOff(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
<ide> }
<ide> |
|
JavaScript | mit | f1721904d43437ee7ec30c33db391f891bbb8847 | 0 | jacksonrayhamilton/p.js | /*jshint node: true */
'use strict';
var p = require('./build/p.commonjs.js');
module.exports = {
deferred: p.defer,
resolved: p.resolve,
rejected: p.reject
};
| adapter.js | /*jshint node: true */
'use strict';
var p = require('./build/p.commonjs.js');
module.exports = {
deferred: function () {
return p.defer();
},
resolved: p.resolve,
rejected: p.reject
};
| Simplify adapter.
| adapter.js | Simplify adapter. | <ide><path>dapter.js
<ide> var p = require('./build/p.commonjs.js');
<ide>
<ide> module.exports = {
<del> deferred: function () {
<del> return p.defer();
<del> },
<add> deferred: p.defer,
<ide> resolved: p.resolve,
<ide> rejected: p.reject
<ide> }; |
|
JavaScript | mit | 5f092345fb165ac7ad89af314b2b790e83b115a6 | 0 | sebweaver/ember-localforage-adapter,tchak/ember-offline-adapter,tchak/ember-offline-adapter,Flexberry/ember-localforage-adapter,Flexberry/ember-localforage-adapter,sebweaver/ember-localforage-adapter,igorrKurr/ember-localforage-adapter,igorrKurr/ember-localforage-adapter | import Ember from 'ember';
export default Ember.Object.extend ({
data : [],
clear : function () {
this.data = [];
},
get : function (namespace) {
if (this.data[namespace]) {
return Ember.copy(this.data[namespace], true);
} else {
return null;
}
},
set : function (namespace, objects) {
this.data[namespace] = objects;
},
replace : function (data) {
this.data = data;
}
}); | addon/utils/cache.js | import Ember from 'ember';
export default Ember.Object.extend ({
data : [],
clear : function () {
this.data = [];
},
get : function (namespace) {
if (this.data[namespace]) {
return this.data[namespace];
} else {
return null;
}
},
set : function (namespace, objects) {
this.data[namespace] = objects;
},
replace : function (data) {
this.data = data;
}
}); | Fixes isssue #13
| addon/utils/cache.js | Fixes isssue #13 | <ide><path>ddon/utils/cache.js
<ide>
<ide> get : function (namespace) {
<ide> if (this.data[namespace]) {
<del> return this.data[namespace];
<add> return Ember.copy(this.data[namespace], true);
<ide> } else {
<ide> return null;
<ide> } |
|
JavaScript | mit | 7d487336e5bcf20ce6185f494032168f0c2d8534 | 0 | frandallfarmer/neohabitat,TheCarlSaganExpress/neohabitat,ssalevan/neohabitat,ssalevan/neohabitat,TheCarlSaganExpress/neohabitat,TheCarlSaganExpress/neohabitat,TheCarlSaganExpress/neohabitat,frandallfarmer/neohabitat,ssalevan/neohabitat,frandallfarmer/neohabitat,frandallfarmer/neohabitat,TheCarlSaganExpress/neohabitat,TheCarlSaganExpress/neohabitat,frandallfarmer/neohabitat,ssalevan/neohabitat,ssalevan/neohabitat,frandallfarmer/neohabitat,ssalevan/neohabitat | /**
* 1986 Habitat and 2016 Elko don't speak the same protocol.
*
* Until we can extend Elko appropriately, we'll use this proxy to translate between
* the protocols.
*
* This bridge does two different things:
* 1) Translates Binary Habitat Protocol to Elko JSON packets
* 2) Deals with various differences in client-server handshaking models,
* such as Habitat server managed region changes vs. client requested context changes.
*
*/
/* jslint bitwise: true */
/* jshint esversion: 6 */
const Net = require('net');
const File = require('fs');
const Trace = require('winston');
const MongoClient = require('mongodb').MongoClient;
const Assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const DefDefs = { context: 'context-test',
listen: '127.0.0.1:1337',
elko: '127.0.0.1:9000',
mongo: '127.0.0.1:27017/elko',
rate: 1200,
realm: 'Popustop',
trace: 'info'};
var Defaults = DefDefs;
try {
var userDefs = JSON.parse(File.readFileSync("defaults.elko"));
Defaults = {
context: userDefs.context || DefDefs.context,
listen: userDefs.listen || DefDefs.listen,
elko: userDefs.elko || DefDefs.elko,
mongo: userDefs.mongo || DefDefs.mongo,
rate: userDefs.rate || DefDefs.rate,
realm: userDefs.realm || DefDefs.realm,
trace: userDefs.trace || DefDefs.trace};
} catch (e) {
console.log("Missing/invalid defaults.elko configuration file. Proceeding with factory defaults.");
}
const Argv = require('yargs')
.usage('Usage: $0 [options]')
.help('help')
.option('help', { alias: '?', describe: 'Get this usage/help information'})
.option('trace', { alias: 't', default: Defaults.trace, describe: 'Trace level name. (see: npm winston)'})
.option('context', { alias: 'c', default: Defaults.context, describe: 'Parameter for entercontext for unknown users'})
.option('listen', { alias: 'l', default: Defaults.listen, describe: 'Host:Port to listen for client connections'})
.option('elko', { alias: 'e', default: Defaults.elko, describe: 'Host:Port of the Habitat Elko Server'})
.option('mongo', { alias: 'm', default: Defaults.mongo, describe: 'Mongodb server URL'})
.option('rate', { alias: 'r', default: Defaults.rate, describe: 'Data rate in bits-per-second for transmitting to c64 clients'})
.option('realm', { alias: 'a', default: Defaults.realm, describe: 'Realm within which to assign turfs'})
.argv;
Trace.level = Argv.trace;
const HCode = require('./hcode');
const Millis = 1000;
const UFILENAME = "./usersDB.json";
var Users = {};
try {
Users = JSON.parse(File.readFileSync(UFILENAME));
} catch (e) { /* do nothing */ }
var listenaddr = Argv.listen.split(":");
var elkoaddr = Argv.elko.split(":");
var ListenHost = listenaddr[0];
var ListenPort = listenaddr.length > 1 ? parseInt(listenaddr[1]) : 1337;
var ElkoHost = elkoaddr[0];
var ElkoPort = elkoaddr.length > 1 ? parseInt(elkoaddr[1]) : 9000;
var SessionCount = 0;
var MongoDB = {};
const UNASSIGNED_NOID = 256;
function rnd(max) {
return Math.floor(Math.random() * max)
}
function findOne(db, query, callback) {
db.collection('odb').findOne(query, callback);
}
function userHasTurf(user) {
return (
user.mods[0].turf !== undefined &&
user.mods[0].turf != "" &&
user.mods[0].turf != "context-test"
);
}
function ensureTurfAssigned(db, userRef, callback) {
db.collection('odb').findOne({
"ref": userRef
}, function(err, user) {
Assert.equal(err, null);
Assert.notEqual(user, null);
// Don't assign a turf Region -to a User if one is already assigned.
if (userHasTurf(user)) {
Trace.debug("User %s already has a turf Region assigned: %s",
userRef, user.mods[0].turf);
callback();
return;
}
// Searches for an available turf Region and assigns it to the User if found.
db.collection('odb').findOne({
"mods.0.type": "Region",
"mods.0.realm": Argv.realm,
"mods.0.is_turf": true,
$or: [
{ "mods.0.resident": { $exists: false } },
{ "mods.0.resident": "" }
]
}, function(err, region) {
Assert.equal(err, null);
if (region === null) {
Trace.error("Unable to find an available turf Region for User: %j", user);
callback();
return;
}
Trace.debug("Assigning turf Region %s to Avatar %s", region.ref, user.ref);
// Assigns the available region as the given user's turf.
user.mods[0]['turf'] = region.ref;
region.mods[0]['resident'] = user.ref;
// Updates the User's Elko document with the turf assignment.
db.collection('odb').updateOne(
{ref: region.ref},
region,
{upsert: true},
function(err, result) {
Assert.equal(err, null);
db.collection('odb').updateOne(
{ref: user.ref},
user,
{upsert: true},
function(err, result) {
Assert.equal(err, null);
callback();
});
});
});
});
}
function insertUser(db, user, callback) {
db.collection('odb').updateOne(
{ref: user.ref},
user,
{upsert: true},
function(err, result) {
Assert.equal(err, null);
callback();
});
}
function addDefaultHead(db, userRef, fullName) {
headRef = "item-head" + Math.random();
db.collection('odb').insertOne({
"ref": headRef,
"type": "item",
"name": "Default head for " + fullName,
"in":userRef,
"mods": [
{
"type": "Head",
"y": 6,
"style": rnd(220),
"orientation": rnd(3) * 8
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + headRef + " for " + userRef);
}
}
)
}
function addPaperPrime(db, userRef, fullName) {
paperRef = "item-paper" + Math.random();
db.collection('odb').insertOne({
"ref": paperRef,
"type": "item",
"name": "Paper for " + fullName,
"in":userRef,
"mods": [
{
"type": "Paper",
"y": 4,
"orientation": 16
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + paperRef + " for " + userRef);
}
}
)
}
function addDefaultTokens(db, userRef, fullName) {
tokenRef = "item-tokens" + Math.random();
db.collection('odb').insertOne({
"ref": tokenRef,
"type": "item",
"name": "Money for " + fullName,
"in":userRef,
"mods": [
{
"type": "Tokens",
"y": 0,
"denom_lo": 0,
"denom_hi": 4
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + tokenRef + " for " + userRef);
}
}
)
}
function confirmOrCreateUser(fullName) {
var userRef = "user-" + fullName.toLowerCase().replace(/ /g,"_");
MongoClient.connect("mongodb://" + Argv.mongo, function(err, db) {
Assert.equal(null, err);
findOne(db, {ref: userRef}, function(err, result) {
if (result === null || Argv.force) {
var newUser = {
"type": "user",
"ref": userRef,
"name": fullName,
"mods": [
{
"type": "Avatar",
"x": 10,
"y": 128 + rnd(32),
"bodyType": "male",
"bankBalance": 50000,
"custom": [rnd(15) + rnd(15)*16, rnd(15) + rnd(15)*16],
"nitty_bits": 0
}
]
};
insertUser(db, newUser, function() {
addDefaultHead(db, userRef, fullName);
addPaperPrime(db, userRef, fullName);
addDefaultTokens(db, userRef, fullName);
ensureTurfAssigned(db, userRef, function() {
db.close();
});
});
} else {
ensureTurfAssigned(db, userRef, function() {
db.close();
});
}
});
});
return userRef;
}
String.prototype.getBytes = function () {
var bytes = [];
for (var i = 0; i < this.length; ++i) {
bytes.push(this.charCodeAt(i));
}
return bytes;
};
/**
* These are byte packets, and you needed to make sure to escape your terminator/unsendables.
*
* @param b {buffer} The characters in the message to be escaped
* @returns encoded char array
*
*/
function escape(b, zero) {
zero = zero || false;
var r = [];
for (var i = 0; i < b.length; i++) {
var c = b[i];
if (c === HCode.END_OF_MESSAGE || c === HCode.ESCAPE_CHAR || (zero && c === 0)) {
r[r.length] = HCode.ESCAPE_CHAR;
c ^= HCode.ESCAPE_XOR;
}
r[r.length] = c;
}
return r;
}
/**
* These were byte packets, and you needed to make sure to escape your terminator/unsendables.
*
* @param b {buffer} The characters in the message to be escaped
* @returns decoded char array
*/
function descape(b, skip) {
var r = [];
var i = skip || 0;
while (i < b.length) {
var c = b[i];
if (c === HCode.ESCAPE_CHAR) {
i++;
c = b[i] ^ HCode.ESCAPE_XOR;
}
r[r.length] = c;
i++;
}
return r;
}
/*
* Elko uses a fresh connection for every context/region change.
*/
function createServerConnection(port, host, client, immediate, context) {
var server = Net.connect({port: port, host:host}, function() {
Trace.debug( "Connecting: " +
client.address().address +':'+ client.address().port +
" <-> " +
server.address().address + ':'+ server.address().port);
if (immediate) {
enterContext(client, server, context);
}
});
server.on('data', function(data) {
var reset = false;
try {
reset = processIncomingElkoBlob(client, server, data);
} catch(err) {
Trace.error("\n\n\nServer input processing error captured:\n" +
err.message + "\n" +
err.stack + "\n" +
"...resuming...\n");
}
if (reset) { // This connection has been replaced due to context change.
Trace.debug("Destroying connection: " + server.address().address + ':' + server.address().port);
// Make sure any outgoing messages have been sent...
var now = new Date().getTime();
var when = Math.ceil(client.timeLastSent + client.lastSentLen * 8 / Argv.rate * Millis);
if (when <= now) {
server.destroy();
} else {
var delay = Math.ceil(Math.max(0, (when - now)));
setTimeout(function () { server.destroy(); }, delay);
}
}
});
// If we see a socket exception, logs it instead of throwing it.
server.on('error', function(err) {
Trace.warn("Unable to connect to NeoHabitat Server, terminating client connection.");
if (client) {
if (client.userName) {
Users[client.userName].online = false;
}
client.end();
}
});
// What if the Elko server breaks the connection? For now we tear the bridge down also.
// If we ever bring up a "director" based service, this will need to change on context changes.
server.on('end', function() {
Trace.debug('Elko port disconnected...');
if (client) {
Trace.debug("{Bridge being shutdown...}");
if (client.userName) {
Users[client.userName].online = false;
}
client.end();
}
});
client.removeAllListeners('data').on('data', function(data) {
try {
parseIncomingHabitatClientMessage(client, server, data);
} catch(err) {
Trace.error("\n\n\nClient input processing error captured:\n" +
JSON.stringify(err,null,2) + "\n" +
err.stack + "\n...resuming...\n");
}
});
client.removeAllListeners('close').on('close', function(data) {
Trace.debug("Habitat client disconnected.");
if (server) {
server.end();
}
});
}
function isString(data) {
return (typeof data === 'string' || data instanceof String);
}
function guardedWrite(connection, msg) {
try {
connection.rawWrite(msg);
} catch (e) {
Trace.warn(e.toString());
}
}
function futureSend(connection, data) {
var now = new Date().getTime();
var when = Math.ceil(connection.timeLastSent + connection.lastSentLen * 8 / Argv.rate * Millis);
connection.lastSentLen = data.length;
if (when <= now) {
connection.write(data);
connection.timeLastSent = now;
} else {
var delay = Math.ceil(Math.max(0, (when - now)));
var msg = (isString(data)) ? data : Buffer.from(escape(data));
setTimeout(function () { guardedWrite(connection, msg); }, delay);
connection.timeLastSent = when;
}
}
function toHabitat(connection, data, split) {
split = split || false;
if (connection.json) {
connection.write(JSON.stringify(data));
connection.write(connection.frame);
} else {
var header = data.slice(0,4);
if (split) {
var payload = data.slice(4);
for (var start = 0; start < payload.length; start += HCode.MAX_PACKET_SIZE) {
var bytes = payload.slice(start);
var size = Math.min(HCode.MAX_PACKET_SIZE, bytes.length);
var seqbyte = header[1] & HCode.SPLIT_MASK;
var bs = "";
if (start === 0) {
seqbyte |= HCode.SPLIT_START;
bs += "START ";
}
seqbyte |= HCode.SPLIT_MIDDLE;
bs += "MIDDLE ";
if (size === bytes.length) {
seqbyte |= HCode.SPLIT_END;
bs += "END";
}
header[1] = seqbyte;
futureSend(connection, connection.packetPrefix);
futureSend(connection, header);
futureSend(connection, bytes.slice(0, size));
futureSend(connection, connection.frame);
}
} else {
futureSend(connection, connection.packetPrefix);
futureSend(connection, data);
futureSend(connection, connection.frame);
}
}
}
function habitatPacketHeader(start, end, seq, noid, reqNum) {
var r = [];
r[0] = HCode.MICROCOSM_ID_BYTE;
r[1] = (seq | (end ? 0x80 : 0x00) | 0x40 | (start ? 0x20 : 0x00)) & HCode.BYTE_MASK;
if (undefined !== noid) {r[2] = noid & HCode.BYTE_MASK; }
if (undefined !== reqNum) {r[3] = reqNum & HCode.BYTE_MASK; }
return r;
}
function habitatAsyncPacketHeader(start, end, noid, reqNum) {
return habitatPacketHeader(start, end, 0x1A, noid, reqNum);
}
var HabBuf = function (start, end, seq, noid, reqNum) {
this.data = [];
if (undefined !== start) {
this.data = this.data.concat(habitatPacketHeader(start, end, seq, noid, reqNum));
}
this.send = function (client, split) {
Trace.debug(JSON.stringify(this.data) + " -> client (" + client.sessionName + ")");
toHabitat(client, Buffer.from(this.data, 'binary'), split);
};
this.add = function (val) {
if (Array.isArray(val)) {
this.data = this.data.concat(val);
} else {
this.data.push(val);
}
};
};
var unpackHabitatObject = function (client, o, containerRef) {
var mod = o.obj.mods[0];
o.noid = mod.noid || 0;
o.mod = mod;
o.ref = o.obj.ref;
o.className = mod.type;
o.classNumber = HCode.CLASSES[mod.type] || 0;
if (o.noid == UNASSIGNED_NOID) {
return true; // Ghost Hack: Items/Avatars ghosted have an UNASSIGNED_NOID
}
if (undefined === HCode[mod.type]) {
Trace.error("\n\n*** Attempted to instantiate class '" + o.className + "' which is not supported. Aborted make. ***\n\n");
return false;
}
o.clientMessages = HCode[mod.type].clientMessages;
o.container = client.state.refToNoid[containerRef] || 0;
client.state.objects[o.noid] = o;
client.state.refToNoid[o.ref] = o.noid;
return true;
}
var vectorize = function (client, newObj , containerRef) {
var o = {obj: newObj};
if (undefined == newObj || !unpackHabitatObject(client, o , containerRef)) return null;
var buf = new HabBuf();
buf.add(o.noid);
buf.add(o.classNumber);
buf.add(0);
habitatEncodeElkoModState(o.mod, o.container, buf);
buf.add(0);
return buf.data;
}
var ContentsVector = function (replySeq, noid, ref, type) {
this.container = new HabBuf();
this.noids = [];
this.objects = new HabBuf();
this.containers = {};
this.containerRef = ref;
this.containerNoid = noid;
this.replySeq = (undefined === replySeq) ? HCode.PHANTOM_REQUEST : replySeq;
this.type = (undefined === type) ? HCode.MESSAGE_DESCRIBE : type;
if (undefined !== noid) {
this.containers[noid] = this;
}
this.add = function (o) {
var mod = o.obj.mods[0];
if (undefined === this.containerRef) {
this.containerRef = o.to;
this.containerNoid = mod.noid;
this.containers[this.containerNoid] = this;
}
if (mod.noid !== this.containerNoid) {
habitatEncodeElkoModState(mod, o.container, this.containers[this.containerNoid].objects);
this.containers[this.containerNoid].noids.push(mod.noid, HCode.CLASSES[mod.type]);
} else {
habitatEncodeElkoModState(mod, o.container, this.containers[this.containerNoid].container);
}
};
this.send = function (client) {
var buf = new HabBuf(
true,
true,
this.replySeq,
HCode.REGION_NOID,
this.type);
if (this.type == HCode.MESSAGE_DESCRIBE) {
if (this.container.data[4] == UNASSIGNED_NOID) {
av = client.state.avatar; // Since the region arrives before the avatar, we need to fix some state...
this.container.data[4] = av.amAGhost ? 255 : av.noid;
this.container.data[8] = ((av.bankBalance & 0xFF000000) >> 24);
this.container.data[7] = ((av.bankBalance & 0x00FF0000) >> 16);
this.container.data[6] = ((av.bankBalance & 0x0000FF00) >> 8);
this.container.data[5] = ((av.bankBalance & 0x000000FF));
}
buf.add(this.container.data);
}
buf.add(this.noids);
buf.add(0);
buf.add(this.objects.data);
buf.add(0);
buf.send(client, true);
};
};
function toElko(connection, data) {
connection.write(data + "\n\n");
}
function initializeClientState(client, who, replySeq) {
++SessionCount;
client.sessionName = "" + SessionCount;
client.state = { user: who || "",
contentsVector: new ContentsVector(replySeq, HCode.REGION_NOID),
objects: [],
refToNoid: {},
numAvatars: 0,
waitingForAvatar: true,
waitingForAvatarContents: false,
otherContents: [],
otherNoid: 0,
otherRef: "",
ghost: false,
replySeq: replySeq
};
}
/**
*
* @param client
* @param server
* @param data
*/
function parseIncomingHabitatClientMessage(client, server, data) {
var send = data.toString().trim();
// Handle new connections - determine the protocol/device type and setup environment
if (undefined === client.json) {
initializeClientState(client);
var curly = send.indexOf("{");
var colon = send.indexOf(":");
if (curly !== -1 && curly < colon) {
client.json = true;
client.binary = false;
client.frame = "\n\n";
} else if (colon !== -1) { // Hacked Qlink bridge doesn't send QLink header, but a user-string instead.
client.packetPrefix = send.substring(0, colon + 1);
client.json = false;
client.binary = true;
client.frame = String.fromCharCode(HCode.END_OF_MESSAGE);
// overload write function to do handle escape!
client.rawWrite = client.write;
client.write = function(msg) {
if (isString(msg)) {
client.rawWrite(msg);
} else {
client.rawWrite(Buffer.from(escape(msg)));
}
};
client.userRef = confirmOrCreateUser(send.substring(0, colon)); // Make sure there's one in the NeoHabitat/Elko database.
Trace.debug(client.sessionName + " (Habitat Client) connected.");
}
}
// Unpack the message and deal with any special protocol transformations.
if (client.json) {
if (send.indexOf("{") < 0) { return; } // Empty JSON text frame ignore without warning.
var o = {};
try {
o = JSON.parse(send);
if (o && o.op) {
if (o.op === "entercontext") {
Trace.debug(o.user + " is trying to enter region-context " + o.context);
confirmOrCreateUser(o.user.substring("user-".length));
}
}
} catch (e) {
Trace.warn("JSON.parse faiure client (" + client.sessionName + ") -> Ignoring: " + JSON.stringify(send) + "\n" + JSON.stringify(e));
return;
}
Trace.debug(client.sessionName + " -> " + JSON.stringify(o) + " -> server ");
toElko(server, send);
} else if (client.binary) {
parseHabitatClientMessage(client, server, data);
} else {
Trace.debug("client (" + client.sessionName + ") -> Garbage message arrived before protocol resolution. Ignoring: " + JSON.stringify(data));
return;
}
}
function parseHabitatClientMessage(client, server, data) {
var hMsg = descape(data.getBytes(), client.packetPrefix.length + 8);
var seq = hMsg[1] & 0x0F;
var end = ((hMsg[1] & 0x80) === 0x80);
var start = ((hMsg[1] & 0x20) === 0x20);
var noid = hMsg[2] || 0;
var reqNum = hMsg[3] || 0;
var args = hMsg.slice(4);
var msg;
Trace.debug("client (" + client.sessionName + ") -> [noid:" + noid +
" request:" + reqNum + " seq:" + seq + " ... " + JSON.stringify(args) + "]");
if (undefined === client.connected) {
client.state.who = client.packetPrefix;
client.connected = true;
// SHORT CIRCUIT: Direct reply to client without server... It's too early to use this bridge at the object level.
var aliveReply = new HabBuf(true, true, HCode.PHANTOM_REQUEST, HCode.REGION_NOID, HCode.MESSAGE_IM_ALIVE);
aliveReply.add(1 /* SUCCESS */);
aliveReply.add(48 /* "0" */);
aliveReply.add("BAD DISK".getBytes());
aliveReply.send(client);
return;
} else {
if (seq !== HCode.PHANTOM_REQUEST) {
client.state.replySeq = seq; // Save sequence number sent by the client for use with any reply.
}
if (noid === HCode.REGION_NOID) {
if (reqNum === HCode.MESSAGE_DESCRIBE) {
// After a (re)connection, only the first request for a contents vector is valid
var context;
if (undefined === client.state.nextRegion) {
context = Argv.context;
} else if (client.state.nextRegion !== "") {
context = client.state.nextRegion;
} else {
return; // Ignore this request, the client is hanging but a changecontext/immdiate message is coming to fix this.
}
enterContext(client, server, context);
return;
}
}
}
// All special cases are resolved. If we get here, we wanted to send the message as-is to the server to handle.
var o = client.state.objects[noid];
var op = (undefined === o.clientMessages[reqNum]) ? "UNSUPPORTED" : o.clientMessages[reqNum].op;
var ref = o.ref;
msg = {"to":ref, "op":op}; // Default Elko-Habitat message header
if ("UNSUPPORTED" === op) {
Trace.warn("*** Unsupported client message " + reqNum + " for " + ref + ". ***");
return;
}
if (undefined !== HCode.translate[op]) {
client.state.replyEncoder = HCode.translate[op].toClient;
if (undefined !== HCode.translate[op].toServer) {
HCode.translate[op].toServer(args, msg, client, start, end);
if (msg.suppressReply) {
return;
}
}
}
if (msg) {
toElko(server, JSON.stringify(msg));
Trace.debug(JSON.stringify(msg) + " -> server (" + client.sessionName + ")");
}
return;
}
function enterContext(client, server, context) {
var replySeq = (undefined === context) ? HCode.PHANTOM_REQUEST : client.state.replySeq;
var enterContextMessage = {
to: "session",
op: "entercontext",
context: context,
user: client.userRef
}
Trace.debug("Sending 'entercontext' to " + enterContextMessage.context +" on behalf of the Habitat client.");
toElko(server, JSON.stringify(enterContextMessage));
initializeClientState(client, client.userRef, replySeq);
client.state.nextRegion = "";
}
function removeNoidFromClient(client, noid) {
if (noid) {
var o = client.state.objects[noid];
var buf = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.MESSAGE_GOAWAY);
buf.add(noid);
buf.send(client);
delete client.state.refToNoid[o.ref];
delete client.state.objects[noid];
if (o.className === "Avatar") {
client.state.numAvatars--;
}
}
}
var encodeState = {
common: function (state, container, buf) {
if (undefined === buf) {
buf = new HabBuf();
}
buf.add(state.style || 0);
buf.add(state.x || 0);
buf.add(state.y || 0);
buf.add(state.orientation || 0);
buf.add(state.gr_state || 0);
buf.add(container || 0);
return buf;
},
document: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.last_page || 0);
return buf;
},
magical: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.magic_type || 0);
return buf;
},
massive: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.mass || 0);
return buf;
},
toggle: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.on || 0);
return buf;
},
openable: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.open_flags || 0);
buf.add(state.key_lo || 0);
buf.add(state.key_hi || 0);
return buf;
},
walkable: function (state, container, buf) {
buf = this.common(state, container, buf);
// buf.add(state.flat_type || 0); TODO Check to see if this is a server only property.
return buf;
},
polygonal: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.trapezoid_type || 0);
buf.add(state.upper_left_x || 0);
buf.add(state.upper_right_x || 0);
buf.add(state.lower_left_x || 0);
buf.add(state.lower_right_x || 0);
buf.add(state.height || 0);
return buf;
},
Region: function (state, container, buf) {
if (undefined === buf) {
buf = new HabBuf();
}
var bal = state.bankBalance || 0;
buf.add(state.terrain_type || 0);
// Sets default Region lighting at 1 if no lighting specified.
if (state.lighting === undefined) {
buf.add(1);
} else {
buf.add(state.lighting);
}
buf.add(state.depth || 32);
buf.add(state.region_class || 0);
buf.add(state.Who_am_I || UNASSIGNED_NOID);
buf.add(0); // Bank account balance is managed once we get the avatar object for this connection.
buf.add(0);
buf.add(0);
buf.add(0);
return buf;
},
Avatar: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activity || 0);
buf.add(state.action || 0);
buf.add(state.health || 255);
buf.add(state.restrainer|| 0);
buf.add(state.custom || [0, 0]);
return buf;
},
Key: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.key_number_lo || 0);
buf.add(state.key_number_hi || 0);
return buf;
},
Sign: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.ascii);
return buf;
},
Street: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.width);
buf.add(state.height);
return buf;
},
Super_trapezoid: function (state, container, buf) {
buf = this.polygonal(state, container, buf);
buf.add(state.pattern_x_size);
buf.add(state.pattern_y_size);
buf.add(state.pattern);
return buf;
},
Glue: function (state, container, buf) {
buf = this.openable(state, container, buf);
buf.add(state.x_offset_1 || 0 );
buf.add(state.y_offset_1 || 0 );
buf.add(state.x_offset_2 || 0 );
buf.add(state.y_offset_2 || 0 );
buf.add(state.x_offset_3 || 0 );
buf.add(state.y_offset_3 || 0 );
buf.add(state.x_offset_4 || 0 );
buf.add(state.y_offset_4 || 0 );
buf.add(state.x_offset_5 || 0 );
buf.add(state.y_offset_5 || 0 );
buf.add(state.x_offset_6 || 0 );
buf.add(state.y_offset_6 || 0 );
return buf;
},
Die: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.state || 0);
return buf;
},
Drugs: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.count || 0);
return buf;
},
Fake_gun: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.state || 0);
return buf;
},
Flat: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.flat_type || 0);
return buf;
},
Tokens: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.denom_lo);
buf.add(state.denom_hi);
return buf;
},
Bottle: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.filled);
return buf;
},
Teleport: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activeState || 0);
return buf;
},
Picture: function (state, container, buf) {
buf = this.massive(state, container, buf);
buf.add(state.picture || 0);
return buf;
},
Vendo_front: function (state, container, buf) {
buf = this.openable(state, container, buf);
buf.add(state.price_lo || 0);
buf.add(state.display_item || 0);
return buf;
},
Escape_device: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.charge || 0);
return buf;
},
Elevator: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activeState || 0);
return buf;
},
Windup_toy: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.wind_level || 0);
return buf;
},
Magic_lamp: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.lamp_state);
buf.add(state.wisher);
return buf;
},
Amulet: function (state, container, buf) { return (this.common (state, container, buf)); },
Atm: function (state, container, buf) { return (this.common (state, container, buf)); },
Bag: function (state, container, buf) { return (this.openable(state, container, buf)); },
Bed: function (state, container, buf) { return (this.common (state, container, buf)); },
Book: function (state, container, buf) { return (this.document(state, container, buf)); },
Box: function (state, container, buf) { return (this.openable(state, container, buf)); },
Building: function (state, container, buf) { return (this.common (state, container, buf)); },
Bush: function (state, container, buf) { return (this.common (state, container, buf)); },
Chair: function (state, container, buf) { return (this.common (state, container, buf)); },
Chest: function (state, container, buf) { return (this.openable(state, container, buf)); },
Club: function (state, container, buf) { return (this.common (state, container, buf)); },
Coke_machine: function (state, container, buf) { return (this.common (state, container, buf)); },
Compass: function (state, container, buf) { return (this.common (state, container, buf)); },
Couch: function (state, container, buf) { return (this.common (state, container, buf)); },
Countertop: function (state, container, buf) { return (this.openable(state, container, buf)); },
Crystal_ball: function (state, container, buf) { return (this.common (state, container, buf)); },
Display_case: function (state, container, buf) { return (this.openable(state, container, buf)); },
Door: function (state, container, buf) { return (this.openable(state, container, buf)); },
Dropbox: function (state, container, buf) { return (this.common (state, container, buf)); },
Fence: function (state, container, buf) { return (this.common (state, container, buf)); },
Flag: function (state, container, buf) { return (this.massive (state, container, buf)); },
Flashlight: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Floor_lamp: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Fortune_machine:function (state, container, buf) { return (this.common (state, container, buf)); },
Fountain: function (state, container, buf) { return (this.common (state, container, buf)); },
Gemstone: function (state, container, buf) { return (this.magical (state, container, buf)); },
Garbage_can: function (state, container, buf) { return (this.openable(state, container, buf)); },
Ghost: function (state, container, buf) { return (this.common (state, container, buf)); },
Ground: function (state, container, buf) { return (this.walkable(state, container, buf)); },
Gun: function (state, container, buf) { return (this.common (state, container, buf)); },
Head: function (state, container, buf) { return (this.common (state, container, buf)); },
Hole: function (state, container, buf) { return (this.openable(state, container, buf)); },
Hot_tub: function (state, container, buf) { return (this.common (state, container, buf)); },
House_cat: function (state, container, buf) { return (this.common (state, container, buf)); },
Knick_knack: function (state, container, buf) { return (this.magical (state, container, buf)); },
Knife: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_immobile: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_staff: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_wand: function (state, container, buf) { return (this.common (state, container, buf)); },
Matchbook: function (state, container, buf) { return (this.common (state, container, buf)); },
Movie_camera: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Paper: function (state, container, buf) { return (this.common (state, container, buf)); },
Pawn_machine: function (state, container, buf) { return (this.openable(state, container, buf)); },
Plant: function (state, container, buf) { return (this.massive (state, container, buf)); },
Plaque: function (state, container, buf) { return (this.document(state, container, buf)); },
Pond: function (state, container, buf) { return (this.common (state, container, buf)); },
Ring: function (state, container, buf) { return (this.common (state, container, buf)); },
Rock: function (state, container, buf) { return (this.massive (state, container, buf)); },
Roof: function (state, container, buf) { return (this.common (state, container, buf)); },
Safe: function (state, container, buf) { return (this.openable(state, container, buf)); },
Sex_changer: function (state, container, buf) { return (this.common (state, container, buf)); },
Short_sign: function (state, container, buf) { return (this.Sign (state, container, buf)); },
Shovel: function (state, container, buf) { return (this.common (state, container, buf)); },
Sky: function (state, container, buf) { return (this.common (state, container, buf)); },
Spray_can: function (state, container, buf) { return (this.common (state, container, buf)); },
Streetlamp: function (state, container, buf) { return (this.common (state, container, buf)); },
Stun_gun: function (state, container, buf) { return (this.common (state, container, buf)); },
Table: function (state, container, buf) { return (this.openable(state, container, buf)); },
Trapezoid: function (state, container, buf) { return (this.polygonal(state,container, buf)); },
Tree: function (state, container, buf) { return (this.common (state, container, buf)); },
Vendo_inside: function (state, container, buf) { return (this.openable(state, container, buf)); },
Wall: function (state, container, buf) { return (this.common (state, container, buf)); },
Window: function (state, container, buf) { return (this.common (state, container, buf)); }
};
function habitatEncodeElkoModState (state, container, buf) {
return encodeState[state.type](state, container, buf);
}
function diagnosticMessage(client, text, noid) {
noid = noid || REGION_NOID;
var msg = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.SERVER_OPS["OBJECTSPEAK_$"].reqno);
msg.add(noid),
msg.add(text.getBytes());
msg.send(client);
}
function checkpointUsers() {
var save = {};
for (key in Users) {
save[key] = ({regionRef:Users[key].regionRef, userRef:Users[key].userRef});
}
File.writeFile(UFILENAME, JSON.stringify(save, null, 2));
}
function findUser(name) {
name = name.toLowerCase();
for (key in Users) {
if (name == key.toLowerCase()) {
return key;
}
}
return name;
}
function parseIncomingElkoServerMessage(client, server, data) {
var o = {};
try {
o = JSON.parse(data);
} catch (e) {
Trace.warn("JSON.parse faiure server (" + client.sessionName + ") -> Ignoring: " + JSON.stringify(data) + "\n" + JSON.stringify(e));
return;
}
if (o.to === "session") {
if (o.op === "exit") {
var reason = "Server forced exit [" + o.whycode + "] " + o.why;
if (undefined !== client.avatarNoid && client.binary) {
diagnosticMessage(client, reason, client.avatarNoid);
}
Trace.warn(reason);
return;
}
}
if (o.op && o.op === "make" && o.you) { // This connection's avatar has arrived - we have a habitat session!
var name = o.obj.name;
var mod = o.obj.mods[0];
var regionRef = o.to.split("-");
var userRef = o.obj.ref.split("-");
Users[name] = {
regionRef: regionRef[0] + "-" + regionRef[1],
userRef: userRef[0] + "-" + userRef[1],
client: client,
online: true};
checkpointUsers();
client.sessionName += ":" + name;
client.userName = name;
client.avatarNoid = mod.noid;
client.waitingForAvatarContents = true;
}
if (o.type === "changeContext") {
client.state.nextRegion = o.context; // Save for MESSAGE_DESCRIBE to deal with later.
var immediate = o.immediate || false; // Force enterContext after reconnect? aka Client has prematurely sent MESSAGE_DESCRIBE and we ignored it.
createServerConnection(client.port, client.host, client, immediate, o.context);
// create a new connection for the new context
return true; // Signal this connection to die now that it's obsolete.
}
if (o.op === "ready") {
if (client.state.waitingForAvatarContents) {
client.state.waitingForAvatar = false;
client.state.waitingForAvatarContents = false;
if (client.json) { // We might have to tell the server that the avatar is visible - emulating C64 client behavior.
toElko(server, JSON.stringify({ to:o.to, op:"FINGER_IN_QUE"}));
toElko(server, JSON.stringify({ to:o.to, op:"I_AM_HERE"}));
return;
}
for (var i = 0; i < client.state.objects.length; i++) {
var itm = client.state.objects[i];
if (undefined !== itm)
client.state.contentsVector.add(itm);
}
Trace.debug(client.state.user +
" known as object ref " +
client.state.ref +
" in region/context " +
client.state.region +
(client.state.avatar.amAGhost ? " (GHOSTED)." : "."));
client.state.contentsVector.send(client);
client.state.contentsVector = new ContentsVector(); // May be used by HEREIS/makes after region arrival
if (client.state.numAvatars === 1) {
var caughtUpMessage = new HabBuf(true, true, HCode.PHANTOM_REQUEST, HCode.REGION_NOID, HCode.MESSAGE_CAUGHT_UP);
caughtUpMessage.add(1); // TRUE
caughtUpMessage.send(client);
}
return;
}
if (client.state.otherNoid) { // Other avatar needs to go out as one package.
if (client.state.otherNoid != UNASSIGNED_NOID) {
for (var i = 0; i < client.state.otherContents.length; i++) {
if (undefined !== client.state.otherContents[i]) {
client.state.contentsVector.add(client.state.otherContents[i]);
}
}
client.state.contentsVector.send(client); // Suppress client send for ghosted avatar-connections.
}
client.state.otherContents = [];
client.state.otherNoid = 0;
client.state.otherRef = "";
client.state.contentsVector = new ContentsVector();
return;
}
// Eat this, since Elko thinks the region's done and the avatar will arrive later
// Habitat wants the user's avatar as part of the contents vector.
return;
}
// JSON client is just a relay...
if (client.json) {
Trace.debug("server (" + client.sessionName + ") -> " + JSON.stringify(o) + " -> client (" + client.sessionName + ")");
toHabitat(client, o);
return;
}
// NEXT UP, TRANSFORM ANY LOGIC
/* Mapping change region (choosing a canonical direction) to change context
is awkward. Habitat wants to send a NEWREGION command and a canonical
compass direction. Elko wants to respond to the request with permission
to set the user's context to the credentials it supplies, in effect telling
the client to "Ask me again to connect to such-and-such-a-place with these
credentials."
I simply am having the bridge do the extra round trip on behalf of the
Habitat Client.
*/
if (undefined === data || (undefined === o.op && undefined === o.type)) {
Trace.warn("Badly formatted server message! Ignored: " + JSON.stringify(o));
return;
}
Trace.debug("server (" + client.sessionName + ") -> " + JSON.stringify(o));
/* changeContext means that Elko wants the user to request a new context.
The bridge will handle this, as this round-trip doesn't involve the
Habitat client. See the MESSAGE_DESCRIBE to see the followup... */
if (o.op === "delete") {
var target = client.state.refToNoid[o.to];
if (target)
removeNoidFromClient(client, target );
return;
}
if (o.op === "make") {
var mod = o.obj.mods[0];
if (!unpackHabitatObject(client, o, o.to)) return;
if (o.className === "Avatar") {
client.state.numAvatars++;
if (!o.you) {
if (undefined == mod.sittingIn || mod.sittingIn == "") {
o.container = 0;
} else {
o.container = mod.sittingIn; // Pretend this avatar is contained by the seat.
mod.y = mod.sittingSlot;
mod.activity = mod.sittingAction;
mod.action = mod.sittingAction;
}
}
if (!o.you && !client.state.waitingForAvatar) { // Async avatar arrival wants to bunch up contents.
client.state.otherNoid = o.noid;
client.state.otherRef = o.ref;
client.state.otherContents.push(o);
client.state.contentsVector =
new ContentsVector(HCode.PHANTOM_REQUEST, HCode.REGION_NOID, o.to, HCode.MESSAGE_HEREIS);
return;
}
}
if (client.state.waitingForAvatar) {
if (o.you) {
client.state.ref = o.ref;
client.state.region = o.to;
client.state.avatar = mod;
client.state.waitingForAvatarContents = true;
// The next "ready" will build the full contents vector and send it to the client.
}
return;
}
if (client.state.otherNoid != 0) { // Keep building other's content list.
o.container = client.state.otherNoid;
client.state.otherContents.push(o); // This will get sent on "ready"
return
}
// Otherwise this is a simple object that can be sent out one thing at a time.
Trace.debug("server (" + client.sessionName + ") make -> HEREIS");
var buf = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.MESSAGE_HEREIS);
buf.add(o.noid);
buf.add(o.classNumber);
buf.add(0);
habitatEncodeElkoModState(mod, o.container, buf);
buf.add(0);
buf.send(client, true);
return;
}
// End of Special Cases - parse the reply/broadcast/neighbor/private message as a object-command.
encodeAndSendClientMessage(client, o);
}
function encodeAndSendClientMessage(client, o) {
var split = false;
if (o.type === "reply") {
var buf = new HabBuf(true, true, client.state.replySeq, o.noid, o.filler);
if (undefined !== client.state.replyEncoder) {
split = client.state.replyEncoder(o, buf, client);
}
buf.send(client, split);
return;
}
if (undefined !== HCode.SERVER_OPS[o.op]) {
o.reqno = HCode.SERVER_OPS[o.op].reqno;
o.toClient = HCode.SERVER_OPS[o.op].toClient;
var buf = new HabBuf(true, true, HCode.PHANTOM_REQUEST, o.noid, o.reqno);
if (undefined !== o.toClient) {
split = o.toClient(o, buf, client);
}
buf.send(client, split);
return;
} else {
Trace.warn("Message from server headed to binary client not yet converted. IGNORED:\n");
return;
}
}
function processIncomingElkoBlob(client, server, data) {
var framed = false;
var firstEOL = false;
var JSONFrame = "";
var blob = data.toString();
for (var i=0; i < blob.length; i++) {
var c = blob.charCodeAt(i);
if (framed) {
JSONFrame += String.fromCharCode(c);
if (10 === c) {
if (!firstEOL) {
firstEOL = true;
} else {
if (parseIncomingElkoServerMessage(client, server, JSONFrame)) {
return true; // Abort and pass along signal that this connection must reset.
}
framed = false;
firstEOL = false;
JSONFrame = "";
}
}
} else {
if (123 === c) {
framed = true;
firstEOL = false;
JSONFrame = "{";
} else {
Trace.warn("IGNORED: " + c);
}
}
}
if (framed) {
Trace.error("INCOMPLETE FRAME: " + JSONFrame);
}
}
//Create a server instance, and chain the listen function to it
//The function passed to net.createServer() becomes the event handler for the 'connection' event
//The sock object the callback function receives is UNIQUE for each connection
const Listener = Net.createServer(function(client) {
// We have a Habitat Client connection!
client.setEncoding('binary');
client.state = {};
client.port = ElkoPort;
client.host = ElkoHost;
client.timeLastSent = new Date().getTime();
client.lastSentLen = 0;
client.backdoor = {vectorize: vectorize}
Trace.debug('Habitat connection from ' + client.address().address + ':'+ client.address().port);
try {
createServerConnection(client.port, client.host, client);
} catch (e) {
Trace.error(e.toString());
}
}).listen(ListenPort, ListenHost);
Trace.info('Habitat to Elko Bridge listening on ' + ListenHost +':'+ ListenPort);
| bridge/Habitat2ElkoBridge.js | /**
* 1986 Habitat and 2016 Elko don't speak the same protocol.
*
* Until we can extend Elko appropriately, we'll use this proxy to translate between
* the protocols.
*
* This bridge does two different things:
* 1) Translates Binary Habitat Protocol to Elko JSON packets
* 2) Deals with various differences in client-server handshaking models,
* such as Habitat server managed region changes vs. client requested context changes.
*
*/
/* jslint bitwise: true */
/* jshint esversion: 6 */
const Net = require('net');
const File = require('fs');
const Trace = require('winston');
const MongoClient = require('mongodb').MongoClient;
const Assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const DefDefs = { context: 'context-test',
listen: '127.0.0.1:1337',
elko: '127.0.0.1:9000',
mongo: '127.0.0.1:27017/elko',
rate: 1200,
trace: 'info'};
var Defaults = DefDefs;
try {
var userDefs = JSON.parse(File.readFileSync("defaults.elko"));
Defaults = {
context: userDefs.context || DefDefs.context,
listen: userDefs.listen || DefDefs.listen,
elko: userDefs.elko || DefDefs.elko,
mongo: userDefs.mongo || DefDefs.mongo,
rate: userDefs.rate || DefDefs.rate,
trace: userDefs.trace || DefDefs.trace};
} catch (e) {
console.log("Missing/invalid defaults.elko configuration file. Proceeding with factory defaults.");
}
const Argv = require('yargs')
.usage('Usage: $0 [options]')
.help('help')
.option('help', { alias: '?', describe: 'Get this usage/help information'})
.option('trace', { alias: 't', default: Defaults.trace, describe: 'Trace level name. (see: npm winston)'})
.option('context', { alias: 'c', default: Defaults.context, describe: 'Parameter for entercontext for unknown users'})
.option('listen', { alias: 'l', default: Defaults.listen, describe: 'Host:Port to listen for client connections'})
.option('elko', { alias: 'e', default: Defaults.elko, describe: 'Host:Port of the Habitat Elko Server'})
.option('mongo', { alias: 'm', default: Defaults.mongo, describe: 'Mongodb server URL'})
.option('rate', { alias: 'r', default: Defaults.rate, describe: 'Data rate in bits-per-second for transmitting to c64 clients'})
.argv;
Trace.level = Argv.trace;
const HCode = require('./hcode');
const Millis = 1000;
const UFILENAME = "./usersDB.json";
var Users = {};
try {
Users = JSON.parse(File.readFileSync(UFILENAME));
} catch (e) { /* do nothing */ }
var listenaddr = Argv.listen.split(":");
var elkoaddr = Argv.elko.split(":");
var ListenHost = listenaddr[0];
var ListenPort = listenaddr.length > 1 ? parseInt(listenaddr[1]) : 1337;
var ElkoHost = elkoaddr[0];
var ElkoPort = elkoaddr.length > 1 ? parseInt(elkoaddr[1]) : 9000;
var SessionCount = 0;
var MongoDB = {};
const UNASSIGNED_NOID = 256;
function rnd(max) {
return Math.floor(Math.random() * max)
}
function findOne(db, query, callback) {
db.collection('odb').findOne(query, callback);
}
function insertUser(db, user, callback) {
db.collection('odb').updateOne(
{ref: user.ref},
user,
{upsert: true},
function(err, result) {
Assert.equal(err, null);
callback();
});
}
function addDefaultHead(db, userRef, fullName) {
headRef = "item-head" + Math.random();
db.collection('odb').insertOne({
"ref": headRef,
"type": "item",
"name": "Default head for " + fullName,
"in":userRef,
"mods": [
{
"type": "Head",
"y": 6,
"style": rnd(220),
"orientation": rnd(3) * 8
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + headRef + " for " + userRef);
}
}
)
}
function addPaperPrime(db, userRef, fullName) {
paperRef = "item-paper" + Math.random();
db.collection('odb').insertOne({
"ref": paperRef,
"type": "item",
"name": "Paper for " + fullName,
"in":userRef,
"mods": [
{
"type": "Paper",
"y": 4,
"orientation": 16
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + paperRef + " for " + userRef);
}
}
)
}
function addDefaultTokens(db, userRef, fullName) {
tokenRef = "item-tokens" + Math.random();
db.collection('odb').insertOne({
"ref": tokenRef,
"type": "item",
"name": "Money for " + fullName,
"in":userRef,
"mods": [
{
"type": "Tokens",
"y": 0,
"denom_lo": 0,
"denom_hi": 4
}
]
}, function(err, result) {
Assert.equal(err, null);
if (result === null) {
Trace.debug("Unable to add " + tokenRef + " for " + userRef);
}
}
)
}
function confirmOrCreateUser(fullName) {
var userRef = "user-" + fullName.toLowerCase().replace(/ /g,"_");
MongoClient.connect("mongodb://" + Argv.mongo, function(err, db) {
Assert.equal(null, err);
findOne(db, {ref: userRef}, function(err, result) {
if (result === null || Argv.force) {
insertUser(db, {
"type": "user",
"ref": userRef,
"name": fullName,
"mods": [
{
"type": "Avatar",
"x": 10,
"y": 128 + rnd(32),
"bodyType": "male",
"bankBalance": 50000,
"custom": [rnd(15) + rnd(15)*16, rnd(15) + rnd(15)*16],
"nitty_bits": 0
}
]
}, function() {
addDefaultHead(db, userRef, fullName);
addPaperPrime(db, userRef, fullName);
addDefaultTokens(db, userRef, fullName);
db.close();
});
} else {
db.close();
}
});
});
return userRef;
}
String.prototype.getBytes = function () {
var bytes = [];
for (var i = 0; i < this.length; ++i) {
bytes.push(this.charCodeAt(i));
}
return bytes;
};
/**
* These are byte packets, and you needed to make sure to escape your terminator/unsendables.
*
* @param b {buffer} The characters in the message to be escaped
* @returns encoded char array
*
*/
function escape(b, zero) {
zero = zero || false;
var r = [];
for (var i = 0; i < b.length; i++) {
var c = b[i];
if (c === HCode.END_OF_MESSAGE || c === HCode.ESCAPE_CHAR || (zero && c === 0)) {
r[r.length] = HCode.ESCAPE_CHAR;
c ^= HCode.ESCAPE_XOR;
}
r[r.length] = c;
}
return r;
}
/**
* These were byte packets, and you needed to make sure to escape your terminator/unsendables.
*
* @param b {buffer} The characters in the message to be escaped
* @returns decoded char array
*/
function descape(b, skip) {
var r = [];
var i = skip || 0;
while (i < b.length) {
var c = b[i];
if (c === HCode.ESCAPE_CHAR) {
i++;
c = b[i] ^ HCode.ESCAPE_XOR;
}
r[r.length] = c;
i++;
}
return r;
}
/*
* Elko uses a fresh connection for every context/region change.
*/
function createServerConnection(port, host, client, immediate, context) {
var server = Net.connect({port: port, host:host}, function() {
Trace.debug( "Connecting: " +
client.address().address +':'+ client.address().port +
" <-> " +
server.address().address + ':'+ server.address().port);
if (immediate) {
enterContext(client, server, context);
}
});
server.on('data', function(data) {
var reset = false;
try {
reset = processIncomingElkoBlob(client, server, data);
} catch(err) {
Trace.error("\n\n\nServer input processing error captured:\n" +
err.message + "\n" +
err.stack + "\n" +
"...resuming...\n");
}
if (reset) { // This connection has been replaced due to context change.
Trace.debug("Destroying connection: " + server.address().address + ':' + server.address().port);
// Make sure any outgoing messages have been sent...
var now = new Date().getTime();
var when = Math.ceil(client.timeLastSent + client.lastSentLen * 8 / Argv.rate * Millis);
if (when <= now) {
server.destroy();
} else {
var delay = Math.ceil(Math.max(0, (when - now)));
setTimeout(function () { server.destroy(); }, delay);
}
}
});
// If we see a socket exception, logs it instead of throwing it.
server.on('error', function(err) {
Trace.warn("Unable to connect to NeoHabitat Server, terminating client connection.");
if (client) {
if (client.userName) {
Users[client.userName].online = false;
}
client.end();
}
});
// What if the Elko server breaks the connection? For now we tear the bridge down also.
// If we ever bring up a "director" based service, this will need to change on context changes.
server.on('end', function() {
Trace.debug('Elko port disconnected...');
if (client) {
Trace.debug("{Bridge being shutdown...}");
if (client.userName) {
Users[client.userName].online = false;
}
client.end();
}
});
client.removeAllListeners('data').on('data', function(data) {
try {
parseIncomingHabitatClientMessage(client, server, data);
} catch(err) {
Trace.error("\n\n\nClient input processing error captured:\n" +
JSON.stringify(err,null,2) + "\n" +
err.stack + "\n...resuming...\n");
}
});
client.removeAllListeners('close').on('close', function(data) {
Trace.debug("Habitat client disconnected.");
if (server) {
server.end();
}
});
}
function isString(data) {
return (typeof data === 'string' || data instanceof String);
}
function guardedWrite(connection, msg) {
try {
connection.rawWrite(msg);
} catch (e) {
Trace.warn(e.toString());
}
}
function futureSend(connection, data) {
var now = new Date().getTime();
var when = Math.ceil(connection.timeLastSent + connection.lastSentLen * 8 / Argv.rate * Millis);
connection.lastSentLen = data.length;
if (when <= now) {
connection.write(data);
connection.timeLastSent = now;
} else {
var delay = Math.ceil(Math.max(0, (when - now)));
var msg = (isString(data)) ? data : Buffer.from(escape(data));
setTimeout(function () { guardedWrite(connection, msg); }, delay);
connection.timeLastSent = when;
}
}
function toHabitat(connection, data, split) {
split = split || false;
if (connection.json) {
connection.write(JSON.stringify(data));
connection.write(connection.frame);
} else {
var header = data.slice(0,4);
if (split) {
var payload = data.slice(4);
for (var start = 0; start < payload.length; start += HCode.MAX_PACKET_SIZE) {
var bytes = payload.slice(start);
var size = Math.min(HCode.MAX_PACKET_SIZE, bytes.length);
var seqbyte = header[1] & HCode.SPLIT_MASK;
var bs = "";
if (start === 0) {
seqbyte |= HCode.SPLIT_START;
bs += "START ";
}
seqbyte |= HCode.SPLIT_MIDDLE;
bs += "MIDDLE ";
if (size === bytes.length) {
seqbyte |= HCode.SPLIT_END;
bs += "END";
}
header[1] = seqbyte;
futureSend(connection, connection.packetPrefix);
futureSend(connection, header);
futureSend(connection, bytes.slice(0, size));
futureSend(connection, connection.frame);
}
} else {
futureSend(connection, connection.packetPrefix);
futureSend(connection, data);
futureSend(connection, connection.frame);
}
}
}
function habitatPacketHeader(start, end, seq, noid, reqNum) {
var r = [];
r[0] = HCode.MICROCOSM_ID_BYTE;
r[1] = (seq | (end ? 0x80 : 0x00) | 0x40 | (start ? 0x20 : 0x00)) & HCode.BYTE_MASK;
if (undefined !== noid) {r[2] = noid & HCode.BYTE_MASK; }
if (undefined !== reqNum) {r[3] = reqNum & HCode.BYTE_MASK; }
return r;
}
function habitatAsyncPacketHeader(start, end, noid, reqNum) {
return habitatPacketHeader(start, end, 0x1A, noid, reqNum);
}
var HabBuf = function (start, end, seq, noid, reqNum) {
this.data = [];
if (undefined !== start) {
this.data = this.data.concat(habitatPacketHeader(start, end, seq, noid, reqNum));
}
this.send = function (client, split) {
Trace.debug(JSON.stringify(this.data) + " -> client (" + client.sessionName + ")");
toHabitat(client, Buffer.from(this.data, 'binary'), split);
};
this.add = function (val) {
if (Array.isArray(val)) {
this.data = this.data.concat(val);
} else {
this.data.push(val);
}
};
};
var unpackHabitatObject = function (client, o, containerRef) {
var mod = o.obj.mods[0];
o.noid = mod.noid || 0;
o.mod = mod;
o.ref = o.obj.ref;
o.className = mod.type;
o.classNumber = HCode.CLASSES[mod.type] || 0;
if (o.noid == UNASSIGNED_NOID) {
return true; // Ghost Hack: Items/Avatars ghosted have an UNASSIGNED_NOID
}
if (undefined === HCode[mod.type]) {
Trace.error("\n\n*** Attempted to instantiate class '" + o.className + "' which is not supported. Aborted make. ***\n\n");
return false;
}
o.clientMessages = HCode[mod.type].clientMessages;
o.container = client.state.refToNoid[containerRef] || 0;
client.state.objects[o.noid] = o;
client.state.refToNoid[o.ref] = o.noid;
return true;
}
var vectorize = function (client, newObj , containerRef) {
var o = {obj: newObj};
if (undefined == newObj || !unpackHabitatObject(client, o , containerRef)) return null;
var buf = new HabBuf();
buf.add(o.noid);
buf.add(o.classNumber);
buf.add(0);
habitatEncodeElkoModState(o.mod, o.container, buf);
buf.add(0);
return buf.data;
}
var ContentsVector = function (replySeq, noid, ref, type) {
this.container = new HabBuf();
this.noids = [];
this.objects = new HabBuf();
this.containers = {};
this.containerRef = ref;
this.containerNoid = noid;
this.replySeq = (undefined === replySeq) ? HCode.PHANTOM_REQUEST : replySeq;
this.type = (undefined === type) ? HCode.MESSAGE_DESCRIBE : type;
if (undefined !== noid) {
this.containers[noid] = this;
}
this.add = function (o) {
var mod = o.obj.mods[0];
if (undefined === this.containerRef) {
this.containerRef = o.to;
this.containerNoid = mod.noid;
this.containers[this.containerNoid] = this;
}
if (mod.noid !== this.containerNoid) {
habitatEncodeElkoModState(mod, o.container, this.containers[this.containerNoid].objects);
this.containers[this.containerNoid].noids.push(mod.noid, HCode.CLASSES[mod.type]);
} else {
habitatEncodeElkoModState(mod, o.container, this.containers[this.containerNoid].container);
}
};
this.send = function (client) {
var buf = new HabBuf(
true,
true,
this.replySeq,
HCode.REGION_NOID,
this.type);
if (this.type == HCode.MESSAGE_DESCRIBE) {
if (this.container.data[4] == UNASSIGNED_NOID) {
av = client.state.avatar; // Since the region arrives before the avatar, we need to fix some state...
this.container.data[4] = av.amAGhost ? 255 : av.noid;
this.container.data[8] = ((av.bankBalance & 0xFF000000) >> 24);
this.container.data[7] = ((av.bankBalance & 0x00FF0000) >> 16);
this.container.data[6] = ((av.bankBalance & 0x0000FF00) >> 8);
this.container.data[5] = ((av.bankBalance & 0x000000FF));
}
buf.add(this.container.data);
}
buf.add(this.noids);
buf.add(0);
buf.add(this.objects.data);
buf.add(0);
buf.send(client, true);
};
};
function toElko(connection, data) {
connection.write(data + "\n\n");
}
function initializeClientState(client, who, replySeq) {
++SessionCount;
client.sessionName = "" + SessionCount;
client.state = { user: who || "",
contentsVector: new ContentsVector(replySeq, HCode.REGION_NOID),
objects: [],
refToNoid: {},
numAvatars: 0,
waitingForAvatar: true,
waitingForAvatarContents: false,
otherContents: [],
otherNoid: 0,
otherRef: "",
ghost: false,
replySeq: replySeq
};
}
/**
*
* @param client
* @param server
* @param data
*/
function parseIncomingHabitatClientMessage(client, server, data) {
var send = data.toString().trim();
// Handle new connections - determine the protocol/device type and setup environment
if (undefined === client.json) {
initializeClientState(client);
var curly = send.indexOf("{");
var colon = send.indexOf(":");
if (curly !== -1 && curly < colon) {
client.json = true;
client.binary = false;
client.frame = "\n\n";
} else if (colon !== -1) { // Hacked Qlink bridge doesn't send QLink header, but a user-string instead.
client.packetPrefix = send.substring(0, colon + 1);
client.json = false;
client.binary = true;
client.frame = String.fromCharCode(HCode.END_OF_MESSAGE);
// overload write function to do handle escape!
client.rawWrite = client.write;
client.write = function(msg) {
if (isString(msg)) {
client.rawWrite(msg);
} else {
client.rawWrite(Buffer.from(escape(msg)));
}
};
client.userRef = confirmOrCreateUser(send.substring(0, colon)); // Make sure there's one in the NeoHabitat/Elko database.
Trace.debug(client.sessionName + " (Habitat Client) connected.");
}
}
// Unpack the message and deal with any special protocol transformations.
if (client.json) {
if (send.indexOf("{") < 0) { return; } // Empty JSON text frame ignore without warning.
var o = {};
try {
o = JSON.parse(send);
if (o && o.op) {
if (o.op === "entercontext") {
Trace.debug(o.user + " is trying to enter region-context " + o.context);
confirmOrCreateUser(o.user.substring("user-".length));
}
}
} catch (e) {
Trace.warn("JSON.parse faiure client (" + client.sessionName + ") -> Ignoring: " + JSON.stringify(send) + "\n" + JSON.stringify(e));
return;
}
Trace.debug(client.sessionName + " -> " + JSON.stringify(o) + " -> server ");
toElko(server, send);
} else if (client.binary) {
parseHabitatClientMessage(client, server, data);
} else {
Trace.debug("client (" + client.sessionName + ") -> Garbage message arrived before protocol resolution. Ignoring: " + JSON.stringify(data));
return;
}
}
function parseHabitatClientMessage(client, server, data) {
var hMsg = descape(data.getBytes(), client.packetPrefix.length + 8);
var seq = hMsg[1] & 0x0F;
var end = ((hMsg[1] & 0x80) === 0x80);
var start = ((hMsg[1] & 0x20) === 0x20);
var noid = hMsg[2] || 0;
var reqNum = hMsg[3] || 0;
var args = hMsg.slice(4);
var msg;
Trace.debug("client (" + client.sessionName + ") -> [noid:" + noid +
" request:" + reqNum + " seq:" + seq + " ... " + JSON.stringify(args) + "]");
if (undefined === client.connected) {
client.state.who = client.packetPrefix;
client.connected = true;
// SHORT CIRCUIT: Direct reply to client without server... It's too early to use this bridge at the object level.
var aliveReply = new HabBuf(true, true, HCode.PHANTOM_REQUEST, HCode.REGION_NOID, HCode.MESSAGE_IM_ALIVE);
aliveReply.add(1 /* SUCCESS */);
aliveReply.add(48 /* "0" */);
aliveReply.add("BAD DISK".getBytes());
aliveReply.send(client);
return;
} else {
if (seq !== HCode.PHANTOM_REQUEST) {
client.state.replySeq = seq; // Save sequence number sent by the client for use with any reply.
}
if (noid === HCode.REGION_NOID) {
if (reqNum === HCode.MESSAGE_DESCRIBE) {
// After a (re)connection, only the first request for a contents vector is valid
var context;
if (undefined === client.state.nextRegion) {
context = Argv.context;
} else if (client.state.nextRegion !== "") {
context = client.state.nextRegion;
} else {
return; // Ignore this request, the client is hanging but a changecontext/immdiate message is coming to fix this.
}
enterContext(client, server, context);
return;
}
}
}
// All special cases are resolved. If we get here, we wanted to send the message as-is to the server to handle.
var o = client.state.objects[noid];
var op = (undefined === o.clientMessages[reqNum]) ? "UNSUPPORTED" : o.clientMessages[reqNum].op;
var ref = o.ref;
msg = {"to":ref, "op":op}; // Default Elko-Habitat message header
if ("UNSUPPORTED" === op) {
Trace.warn("*** Unsupported client message " + reqNum + " for " + ref + ". ***");
return;
}
if (undefined !== HCode.translate[op]) {
client.state.replyEncoder = HCode.translate[op].toClient;
if (undefined !== HCode.translate[op].toServer) {
HCode.translate[op].toServer(args, msg, client, start, end);
if (msg.suppressReply) {
return;
}
}
}
if (msg) {
toElko(server, JSON.stringify(msg));
Trace.debug(JSON.stringify(msg) + " -> server (" + client.sessionName + ")");
}
return;
}
function enterContext(client, server, context) {
var replySeq = (undefined === context) ? HCode.PHANTOM_REQUEST : client.state.replySeq;
var enterContextMessage = {
to: "session",
op: "entercontext",
context: context,
user: client.userRef
}
Trace.debug("Sending 'entercontext' to " + enterContextMessage.context +" on behalf of the Habitat client.");
toElko(server, JSON.stringify(enterContextMessage));
initializeClientState(client, client.userRef, replySeq);
client.state.nextRegion = "";
}
function removeNoidFromClient(client, noid) {
if (noid) {
var o = client.state.objects[noid];
var buf = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.MESSAGE_GOAWAY);
buf.add(noid);
buf.send(client);
delete client.state.refToNoid[o.ref];
delete client.state.objects[noid];
if (o.className === "Avatar") {
client.state.numAvatars--;
}
}
}
var encodeState = {
common: function (state, container, buf) {
if (undefined === buf) {
buf = new HabBuf();
}
buf.add(state.style || 0);
buf.add(state.x || 0);
buf.add(state.y || 0);
buf.add(state.orientation || 0);
buf.add(state.gr_state || 0);
buf.add(container || 0);
return buf;
},
document: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.last_page || 0);
return buf;
},
magical: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.magic_type || 0);
return buf;
},
massive: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.mass || 0);
return buf;
},
toggle: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.on || 0);
return buf;
},
openable: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.open_flags || 0);
buf.add(state.key_lo || 0);
buf.add(state.key_hi || 0);
return buf;
},
walkable: function (state, container, buf) {
buf = this.common(state, container, buf);
// buf.add(state.flat_type || 0); TODO Check to see if this is a server only property.
return buf;
},
polygonal: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.trapezoid_type || 0);
buf.add(state.upper_left_x || 0);
buf.add(state.upper_right_x || 0);
buf.add(state.lower_left_x || 0);
buf.add(state.lower_right_x || 0);
buf.add(state.height || 0);
return buf;
},
Region: function (state, container, buf) {
if (undefined === buf) {
buf = new HabBuf();
}
var bal = state.bankBalance || 0;
buf.add(state.terrain_type || 0);
// Sets default Region lighting at 1 if no lighting specified.
if (state.lighting === undefined) {
buf.add(1);
} else {
buf.add(state.lighting);
}
buf.add(state.depth || 32);
buf.add(state.region_class || 0);
buf.add(state.Who_am_I || UNASSIGNED_NOID);
buf.add(0); // Bank account balance is managed once we get the avatar object for this connection.
buf.add(0);
buf.add(0);
buf.add(0);
return buf;
},
Avatar: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activity || 0);
buf.add(state.action || 0);
buf.add(state.health || 255);
buf.add(state.restrainer|| 0);
buf.add(state.custom || [0, 0]);
return buf;
},
Key: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.key_number_lo || 0);
buf.add(state.key_number_hi || 0);
return buf;
},
Sign: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.ascii);
return buf;
},
Street: function (state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.width);
buf.add(state.height);
return buf;
},
Super_trapezoid: function (state, container, buf) {
buf = this.polygonal(state, container, buf);
buf.add(state.pattern_x_size);
buf.add(state.pattern_y_size);
buf.add(state.pattern);
return buf;
},
Glue: function (state, container, buf) {
buf = this.openable(state, container, buf);
buf.add(state.x_offset_1 || 0 );
buf.add(state.y_offset_1 || 0 );
buf.add(state.x_offset_2 || 0 );
buf.add(state.y_offset_2 || 0 );
buf.add(state.x_offset_3 || 0 );
buf.add(state.y_offset_3 || 0 );
buf.add(state.x_offset_4 || 0 );
buf.add(state.y_offset_4 || 0 );
buf.add(state.x_offset_5 || 0 );
buf.add(state.y_offset_5 || 0 );
buf.add(state.x_offset_6 || 0 );
buf.add(state.y_offset_6 || 0 );
return buf;
},
Die: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.state || 0);
return buf;
},
Drugs: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.count || 0);
return buf;
},
Fake_gun: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.state || 0);
return buf;
},
Flat: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.flat_type || 0);
return buf;
},
Tokens: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.denom_lo);
buf.add(state.denom_hi);
return buf;
},
Bottle: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.filled);
return buf;
},
Teleport: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activeState || 0);
return buf;
},
Picture: function (state, container, buf) {
buf = this.massive(state, container, buf);
buf.add(state.picture || 0);
return buf;
},
Vendo_front: function (state, container, buf) {
buf = this.openable(state, container, buf);
buf.add(state.price_lo || 0);
buf.add(state.display_item || 0);
return buf;
},
Escape_device: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.charge || 0);
return buf;
},
Elevator: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.activeState || 0);
return buf;
},
Windup_toy: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.wind_level || 0);
return buf;
},
Magic_lamp: function(state, container, buf) {
buf = this.common(state, container, buf);
buf.add(state.lamp_state);
buf.add(state.wisher);
return buf;
},
Amulet: function (state, container, buf) { return (this.common (state, container, buf)); },
Atm: function (state, container, buf) { return (this.common (state, container, buf)); },
Bag: function (state, container, buf) { return (this.openable(state, container, buf)); },
Bed: function (state, container, buf) { return (this.common (state, container, buf)); },
Book: function (state, container, buf) { return (this.document(state, container, buf)); },
Box: function (state, container, buf) { return (this.openable(state, container, buf)); },
Building: function (state, container, buf) { return (this.common (state, container, buf)); },
Bush: function (state, container, buf) { return (this.common (state, container, buf)); },
Chair: function (state, container, buf) { return (this.common (state, container, buf)); },
Chest: function (state, container, buf) { return (this.openable(state, container, buf)); },
Club: function (state, container, buf) { return (this.common (state, container, buf)); },
Coke_machine: function (state, container, buf) { return (this.common (state, container, buf)); },
Compass: function (state, container, buf) { return (this.common (state, container, buf)); },
Couch: function (state, container, buf) { return (this.common (state, container, buf)); },
Countertop: function (state, container, buf) { return (this.openable(state, container, buf)); },
Crystal_ball: function (state, container, buf) { return (this.common (state, container, buf)); },
Display_case: function (state, container, buf) { return (this.openable(state, container, buf)); },
Door: function (state, container, buf) { return (this.openable(state, container, buf)); },
Dropbox: function (state, container, buf) { return (this.common (state, container, buf)); },
Fence: function (state, container, buf) { return (this.common (state, container, buf)); },
Flag: function (state, container, buf) { return (this.massive (state, container, buf)); },
Flashlight: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Floor_lamp: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Fortune_machine:function (state, container, buf) { return (this.common (state, container, buf)); },
Fountain: function (state, container, buf) { return (this.common (state, container, buf)); },
Gemstone: function (state, container, buf) { return (this.magical (state, container, buf)); },
Garbage_can: function (state, container, buf) { return (this.openable(state, container, buf)); },
Ghost: function (state, container, buf) { return (this.common (state, container, buf)); },
Ground: function (state, container, buf) { return (this.walkable(state, container, buf)); },
Gun: function (state, container, buf) { return (this.common (state, container, buf)); },
Head: function (state, container, buf) { return (this.common (state, container, buf)); },
Hole: function (state, container, buf) { return (this.openable(state, container, buf)); },
Hot_tub: function (state, container, buf) { return (this.common (state, container, buf)); },
House_cat: function (state, container, buf) { return (this.common (state, container, buf)); },
Knick_knack: function (state, container, buf) { return (this.magical (state, container, buf)); },
Knife: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_immobile: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_staff: function (state, container, buf) { return (this.common (state, container, buf)); },
Magic_wand: function (state, container, buf) { return (this.common (state, container, buf)); },
Matchbook: function (state, container, buf) { return (this.common (state, container, buf)); },
Movie_camera: function (state, container, buf) { return (this.toggle (state, container, buf)); },
Paper: function (state, container, buf) { return (this.common (state, container, buf)); },
Pawn_machine: function (state, container, buf) { return (this.openable(state, container, buf)); },
Plant: function (state, container, buf) { return (this.massive (state, container, buf)); },
Plaque: function (state, container, buf) { return (this.document(state, container, buf)); },
Pond: function (state, container, buf) { return (this.common (state, container, buf)); },
Ring: function (state, container, buf) { return (this.common (state, container, buf)); },
Rock: function (state, container, buf) { return (this.massive (state, container, buf)); },
Roof: function (state, container, buf) { return (this.common (state, container, buf)); },
Safe: function (state, container, buf) { return (this.openable(state, container, buf)); },
Sex_changer: function (state, container, buf) { return (this.common (state, container, buf)); },
Short_sign: function (state, container, buf) { return (this.Sign (state, container, buf)); },
Shovel: function (state, container, buf) { return (this.common (state, container, buf)); },
Sky: function (state, container, buf) { return (this.common (state, container, buf)); },
Spray_can: function (state, container, buf) { return (this.common (state, container, buf)); },
Streetlamp: function (state, container, buf) { return (this.common (state, container, buf)); },
Stun_gun: function (state, container, buf) { return (this.common (state, container, buf)); },
Table: function (state, container, buf) { return (this.openable(state, container, buf)); },
Trapezoid: function (state, container, buf) { return (this.polygonal(state,container, buf)); },
Tree: function (state, container, buf) { return (this.common (state, container, buf)); },
Vendo_inside: function (state, container, buf) { return (this.openable(state, container, buf)); },
Wall: function (state, container, buf) { return (this.common (state, container, buf)); },
Window: function (state, container, buf) { return (this.common (state, container, buf)); }
};
function habitatEncodeElkoModState (state, container, buf) {
return encodeState[state.type](state, container, buf);
}
function diagnosticMessage(client, text, noid) {
noid = noid || REGION_NOID;
var msg = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.SERVER_OPS["OBJECTSPEAK_$"].reqno);
msg.add(noid),
msg.add(text.getBytes());
msg.send(client);
}
function checkpointUsers() {
var save = {};
for (key in Users) {
save[key] = ({regionRef:Users[key].regionRef, userRef:Users[key].userRef});
}
File.writeFile(UFILENAME, JSON.stringify(save, null, 2));
}
function findUser(name) {
name = name.toLowerCase();
for (key in Users) {
if (name == key.toLowerCase()) {
return key;
}
}
return name;
}
function parseIncomingElkoServerMessage(client, server, data) {
var o = {};
try {
o = JSON.parse(data);
} catch (e) {
Trace.warn("JSON.parse faiure server (" + client.sessionName + ") -> Ignoring: " + JSON.stringify(data) + "\n" + JSON.stringify(e));
return;
}
if (o.to === "session") {
if (o.op === "exit") {
var reason = "Server forced exit [" + o.whycode + "] " + o.why;
if (undefined !== client.avatarNoid && client.binary) {
diagnosticMessage(client, reason, client.avatarNoid);
}
Trace.warn(reason);
return;
}
}
if (o.op && o.op === "make" && o.you) { // This connection's avatar has arrived - we have a habitat session!
var name = o.obj.name;
var mod = o.obj.mods[0];
var regionRef = o.to.split("-");
var userRef = o.obj.ref.split("-");
Users[name] = {
regionRef: regionRef[0] + "-" + regionRef[1],
userRef: userRef[0] + "-" + userRef[1],
client: client,
online: true};
checkpointUsers();
client.sessionName += ":" + name;
client.userName = name;
client.avatarNoid = mod.noid;
client.waitingForAvatarContents = true;
}
if (o.type === "changeContext") {
client.state.nextRegion = o.context; // Save for MESSAGE_DESCRIBE to deal with later.
var immediate = o.immediate || false; // Force enterContext after reconnect? aka Client has prematurely sent MESSAGE_DESCRIBE and we ignored it.
createServerConnection(client.port, client.host, client, immediate, o.context);
// create a new connection for the new context
return true; // Signal this connection to die now that it's obsolete.
}
if (o.op === "ready") {
if (client.state.waitingForAvatarContents) {
client.state.waitingForAvatar = false;
client.state.waitingForAvatarContents = false;
if (client.json) { // We might have to tell the server that the avatar is visible - emulating C64 client behavior.
toElko(server, JSON.stringify({ to:o.to, op:"FINGER_IN_QUE"}));
toElko(server, JSON.stringify({ to:o.to, op:"I_AM_HERE"}));
return;
}
for (var i = 0; i < client.state.objects.length; i++) {
var itm = client.state.objects[i];
if (undefined !== itm)
client.state.contentsVector.add(itm);
}
Trace.debug(client.state.user +
" known as object ref " +
client.state.ref +
" in region/context " +
client.state.region +
(client.state.avatar.amAGhost ? " (GHOSTED)." : "."));
client.state.contentsVector.send(client);
client.state.contentsVector = new ContentsVector(); // May be used by HEREIS/makes after region arrival
if (client.state.numAvatars === 1) {
var caughtUpMessage = new HabBuf(true, true, HCode.PHANTOM_REQUEST, HCode.REGION_NOID, HCode.MESSAGE_CAUGHT_UP);
caughtUpMessage.add(1); // TRUE
caughtUpMessage.send(client);
}
return;
}
if (client.state.otherNoid) { // Other avatar needs to go out as one package.
if (client.state.otherNoid != UNASSIGNED_NOID) {
for (var i = 0; i < client.state.otherContents.length; i++) {
if (undefined !== client.state.otherContents[i]) {
client.state.contentsVector.add(client.state.otherContents[i]);
}
}
client.state.contentsVector.send(client); // Suppress client send for ghosted avatar-connections.
}
client.state.otherContents = [];
client.state.otherNoid = 0;
client.state.otherRef = "";
client.state.contentsVector = new ContentsVector();
return;
}
// Eat this, since Elko thinks the region's done and the avatar will arrive later
// Habitat wants the user's avatar as part of the contents vector.
return;
}
// JSON client is just a relay...
if (client.json) {
Trace.debug("server (" + client.sessionName + ") -> " + JSON.stringify(o) + " -> client (" + client.sessionName + ")");
toHabitat(client, o);
return;
}
// NEXT UP, TRANSFORM ANY LOGIC
/* Mapping change region (choosing a canonical direction) to change context
is awkward. Habitat wants to send a NEWREGION command and a canonical
compass direction. Elko wants to respond to the request with permission
to set the user's context to the credentials it supplies, in effect telling
the client to "Ask me again to connect to such-and-such-a-place with these
credentials."
I simply am having the bridge do the extra round trip on behalf of the
Habitat Client.
*/
if (undefined === data || (undefined === o.op && undefined === o.type)) {
Trace.warn("Badly formatted server message! Ignored: " + JSON.stringify(o));
return;
}
Trace.debug("server (" + client.sessionName + ") -> " + JSON.stringify(o));
/* changeContext means that Elko wants the user to request a new context.
The bridge will handle this, as this round-trip doesn't involve the
Habitat client. See the MESSAGE_DESCRIBE to see the followup... */
if (o.op === "delete") {
var target = client.state.refToNoid[o.to];
if (target)
removeNoidFromClient(client, target );
return;
}
if (o.op === "make") {
var mod = o.obj.mods[0];
if (!unpackHabitatObject(client, o, o.to)) return;
if (o.className === "Avatar") {
client.state.numAvatars++;
if (!o.you) {
if (undefined == mod.sittingIn || mod.sittingIn == "") {
o.container = 0;
} else {
o.container = mod.sittingIn; // Pretend this avatar is contained by the seat.
mod.y = mod.sittingSlot;
mod.activity = mod.sittingAction;
mod.action = mod.sittingAction;
}
}
if (!o.you && !client.state.waitingForAvatar) { // Async avatar arrival wants to bunch up contents.
client.state.otherNoid = o.noid;
client.state.otherRef = o.ref;
client.state.otherContents.push(o);
client.state.contentsVector =
new ContentsVector(HCode.PHANTOM_REQUEST, HCode.REGION_NOID, o.to, HCode.MESSAGE_HEREIS);
return;
}
}
if (client.state.waitingForAvatar) {
if (o.you) {
client.state.ref = o.ref;
client.state.region = o.to;
client.state.avatar = mod;
client.state.waitingForAvatarContents = true;
// The next "ready" will build the full contents vector and send it to the client.
}
return;
}
if (client.state.otherNoid != 0) { // Keep building other's content list.
o.container = client.state.otherNoid;
client.state.otherContents.push(o); // This will get sent on "ready"
return
}
// Otherwise this is a simple object that can be sent out one thing at a time.
Trace.debug("server (" + client.sessionName + ") make -> HEREIS");
var buf = new HabBuf(
true,
true,
HCode.PHANTOM_REQUEST,
HCode.REGION_NOID,
HCode.MESSAGE_HEREIS);
buf.add(o.noid);
buf.add(o.classNumber);
buf.add(0);
habitatEncodeElkoModState(mod, o.container, buf);
buf.add(0);
buf.send(client, true);
return;
}
// End of Special Cases - parse the reply/broadcast/neighbor/private message as a object-command.
encodeAndSendClientMessage(client, o);
}
function encodeAndSendClientMessage(client, o) {
var split = false;
if (o.type === "reply") {
var buf = new HabBuf(true, true, client.state.replySeq, o.noid, o.filler);
if (undefined !== client.state.replyEncoder) {
split = client.state.replyEncoder(o, buf, client);
}
buf.send(client, split);
return;
}
if (undefined !== HCode.SERVER_OPS[o.op]) {
o.reqno = HCode.SERVER_OPS[o.op].reqno;
o.toClient = HCode.SERVER_OPS[o.op].toClient;
var buf = new HabBuf(true, true, HCode.PHANTOM_REQUEST, o.noid, o.reqno);
if (undefined !== o.toClient) {
split = o.toClient(o, buf, client);
}
buf.send(client, split);
return;
} else {
Trace.warn("Message from server headed to binary client not yet converted. IGNORED:\n");
return;
}
}
function processIncomingElkoBlob(client, server, data) {
var framed = false;
var firstEOL = false;
var JSONFrame = "";
var blob = data.toString();
for (var i=0; i < blob.length; i++) {
var c = blob.charCodeAt(i);
if (framed) {
JSONFrame += String.fromCharCode(c);
if (10 === c) {
if (!firstEOL) {
firstEOL = true;
} else {
if (parseIncomingElkoServerMessage(client, server, JSONFrame)) {
return true; // Abort and pass along signal that this connection must reset.
}
framed = false;
firstEOL = false;
JSONFrame = "";
}
}
} else {
if (123 === c) {
framed = true;
firstEOL = false;
JSONFrame = "{";
} else {
Trace.warn("IGNORED: " + c);
}
}
}
if (framed) {
Trace.error("INCOMPLETE FRAME: " + JSONFrame);
}
}
//Create a server instance, and chain the listen function to it
//The function passed to net.createServer() becomes the event handler for the 'connection' event
//The sock object the callback function receives is UNIQUE for each connection
const Listener = Net.createServer(function(client) {
// We have a Habitat Client connection!
client.setEncoding('binary');
client.state = {};
client.port = ElkoPort;
client.host = ElkoHost;
client.timeLastSent = new Date().getTime();
client.lastSentLen = 0;
client.backdoor = {vectorize: vectorize}
Trace.debug('Habitat connection from ' + client.address().address + ':'+ client.address().port);
try {
createServerConnection(client.port, client.host, client);
} catch (e) {
Trace.error(e.toString());
}
}).listen(ListenPort, ListenHost);
Trace.info('Habitat to Elko Bridge listening on ' + ListenHost +':'+ ListenPort);
| Adds just-in-time turf Region assignemnt logic
| bridge/Habitat2ElkoBridge.js | Adds just-in-time turf Region assignemnt logic | <ide><path>ridge/Habitat2ElkoBridge.js
<ide> elko: '127.0.0.1:9000',
<ide> mongo: '127.0.0.1:27017/elko',
<ide> rate: 1200,
<add> realm: 'Popustop',
<ide> trace: 'info'};
<ide> var Defaults = DefDefs;
<ide>
<ide> elko: userDefs.elko || DefDefs.elko,
<ide> mongo: userDefs.mongo || DefDefs.mongo,
<ide> rate: userDefs.rate || DefDefs.rate,
<add> realm: userDefs.realm || DefDefs.realm,
<ide> trace: userDefs.trace || DefDefs.trace};
<ide> } catch (e) {
<ide> console.log("Missing/invalid defaults.elko configuration file. Proceeding with factory defaults.");
<ide> .option('elko', { alias: 'e', default: Defaults.elko, describe: 'Host:Port of the Habitat Elko Server'})
<ide> .option('mongo', { alias: 'm', default: Defaults.mongo, describe: 'Mongodb server URL'})
<ide> .option('rate', { alias: 'r', default: Defaults.rate, describe: 'Data rate in bits-per-second for transmitting to c64 clients'})
<add>.option('realm', { alias: 'a', default: Defaults.realm, describe: 'Realm within which to assign turfs'})
<ide> .argv;
<ide>
<ide> Trace.level = Argv.trace;
<ide> db.collection('odb').findOne(query, callback);
<ide> }
<ide>
<add>function userHasTurf(user) {
<add> return (
<add> user.mods[0].turf !== undefined &&
<add> user.mods[0].turf != "" &&
<add> user.mods[0].turf != "context-test"
<add> );
<add>}
<add>
<add>function ensureTurfAssigned(db, userRef, callback) {
<add> db.collection('odb').findOne({
<add> "ref": userRef
<add> }, function(err, user) {
<add> Assert.equal(err, null);
<add> Assert.notEqual(user, null);
<add>
<add> // Don't assign a turf Region -to a User if one is already assigned.
<add> if (userHasTurf(user)) {
<add> Trace.debug("User %s already has a turf Region assigned: %s",
<add> userRef, user.mods[0].turf);
<add> callback();
<add> return;
<add> }
<add>
<add> // Searches for an available turf Region and assigns it to the User if found.
<add> db.collection('odb').findOne({
<add> "mods.0.type": "Region",
<add> "mods.0.realm": Argv.realm,
<add> "mods.0.is_turf": true,
<add> $or: [
<add> { "mods.0.resident": { $exists: false } },
<add> { "mods.0.resident": "" }
<add> ]
<add> }, function(err, region) {
<add> Assert.equal(err, null);
<add> if (region === null) {
<add> Trace.error("Unable to find an available turf Region for User: %j", user);
<add> callback();
<add> return;
<add> }
<add> Trace.debug("Assigning turf Region %s to Avatar %s", region.ref, user.ref);
<add>
<add> // Assigns the available region as the given user's turf.
<add> user.mods[0]['turf'] = region.ref;
<add> region.mods[0]['resident'] = user.ref;
<add>
<add> // Updates the User's Elko document with the turf assignment.
<add> db.collection('odb').updateOne(
<add> {ref: region.ref},
<add> region,
<add> {upsert: true},
<add> function(err, result) {
<add> Assert.equal(err, null);
<add> db.collection('odb').updateOne(
<add> {ref: user.ref},
<add> user,
<add> {upsert: true},
<add> function(err, result) {
<add> Assert.equal(err, null);
<add> callback();
<add> });
<add> });
<add> });
<add> });
<add>}
<ide>
<ide> function insertUser(db, user, callback) {
<ide> db.collection('odb').updateOne(
<ide> Assert.equal(null, err);
<ide> findOne(db, {ref: userRef}, function(err, result) {
<ide> if (result === null || Argv.force) {
<del> insertUser(db, {
<add> var newUser = {
<ide> "type": "user",
<ide> "ref": userRef,
<ide> "name": fullName,
<ide> "custom": [rnd(15) + rnd(15)*16, rnd(15) + rnd(15)*16],
<ide> "nitty_bits": 0
<ide> }
<del> ]
<del> }, function() {
<add> ]
<add> };
<add> insertUser(db, newUser, function() {
<ide> addDefaultHead(db, userRef, fullName);
<ide> addPaperPrime(db, userRef, fullName);
<ide> addDefaultTokens(db, userRef, fullName);
<add> ensureTurfAssigned(db, userRef, function() {
<add> db.close();
<add> });
<add> });
<add> } else {
<add> ensureTurfAssigned(db, userRef, function() {
<ide> db.close();
<ide> });
<del> } else {
<del> db.close();
<ide> }
<ide> });
<ide> });
<add>
<ide> return userRef;
<ide> }
<ide> |
|
Java | lgpl-2.1 | error: pathspec 'src/org/mapyrus/Argument.java' did not match any file(s) known to git
| ef6b3c048949ddf97fa6ad2fbd3ef9499f453be0 | 1 | simoc/mapyrus,simoc/mapyrus,simoc/mapyrus | /**
* An argument is a literal value or variable name.
* Several arguments are combined with operators to make an expression.
*/
/*
* $Id$
*/
import java.lang.String;
public class Argument
{
public static final int NUMERIC = 0;
public static final int STRING = 1;
public static final int VARIABLE = 2;
private int mType;
private double mNumericValue;
private String mStringValue;
private String mVarname;
/**
* Create a new numeric argument.
* @param d is value for this argument.
*/
public Argument(double d)
{
mType = NUMERIC;
mNumericValue = d;
}
/**
* Create a new string argument or variable name.
* @param type is STRING to create a string argument, or VARIABLE to create
* a reference to a variable.
*/
public Argument(int type, String s)
{
mType = type;
if (type == STRING)
mStringValue = s;
else
mVarname = s;
}
/**
* Returns type of argument.
* @return either NUMERIC, STRING, or VARIABLE.
*/
public int getType()
{
return(mType);
}
/**
* Returns value of numeric argument.
* @return numeric argument value.
*/
public double getNumericValue()
{
return(mNumericValue);
}
/**
* Returns value of string argument.
* @return string argument value.
*/
public String getStringValue()
{
return(mStringValue);
}
/**
* Returns variable name reference of argument.
* @return name of variable containing value for this argument.
*/
public String getVariableName()
{
return(mVarname);
}
}
| src/org/mapyrus/Argument.java | Initial revision
| src/org/mapyrus/Argument.java | Initial revision | <ide><path>rc/org/mapyrus/Argument.java
<add>/**
<add> * An argument is a literal value or variable name.
<add> * Several arguments are combined with operators to make an expression.
<add> */
<add>
<add>/*
<add> * $Id$
<add> */
<add>import java.lang.String;
<add>
<add>public class Argument
<add>{
<add> public static final int NUMERIC = 0;
<add> public static final int STRING = 1;
<add> public static final int VARIABLE = 2;
<add>
<add> private int mType;
<add> private double mNumericValue;
<add> private String mStringValue;
<add> private String mVarname;
<add>
<add> /**
<add> * Create a new numeric argument.
<add> * @param d is value for this argument.
<add> */
<add> public Argument(double d)
<add> {
<add> mType = NUMERIC;
<add> mNumericValue = d;
<add> }
<add>
<add> /**
<add> * Create a new string argument or variable name.
<add> * @param type is STRING to create a string argument, or VARIABLE to create
<add> * a reference to a variable.
<add> */
<add> public Argument(int type, String s)
<add> {
<add> mType = type;
<add> if (type == STRING)
<add> mStringValue = s;
<add> else
<add> mVarname = s;
<add> }
<add>
<add> /**
<add> * Returns type of argument.
<add> * @return either NUMERIC, STRING, or VARIABLE.
<add> */
<add> public int getType()
<add> {
<add> return(mType);
<add> }
<add>
<add> /**
<add> * Returns value of numeric argument.
<add> * @return numeric argument value.
<add> */
<add> public double getNumericValue()
<add> {
<add> return(mNumericValue);
<add> }
<add>
<add> /**
<add> * Returns value of string argument.
<add> * @return string argument value.
<add> */
<add> public String getStringValue()
<add> {
<add> return(mStringValue);
<add> }
<add>
<add> /**
<add> * Returns variable name reference of argument.
<add> * @return name of variable containing value for this argument.
<add> */
<add> public String getVariableName()
<add> {
<add> return(mVarname);
<add> }
<add>} |
|
Java | apache-2.0 | 77f4c7fe8084031301ecdfdf8e2e216dcce16d5a | 0 | xiaolei/transaction | package io.github.xiaolei.transaction.ui;
import io.github.xiaolei.enterpriselibrary.widget.FragmentViewPager;
import io.github.xiaolei.transaction.entity.Product;
/**
* TODO: add comment
*/
public interface IFragmentSwitchable {
FragmentViewPager getFragmentSwitcher();
void switchToProductEditor(long productId);
void switchToTagEditor(long tagId);
void switchToTagList();
void switchToProductList(boolean reload, boolean isSelectionMode);
void switchToCalculator(Product product);
}
| app/src/main/java/io/github/xiaolei/transaction/ui/IFragmentSwitchable.java | package io.github.xiaolei.transaction.ui;
import io.github.xiaolei.enterpriselibrary.widget.FragmentViewPager;
import io.github.xiaolei.transaction.entity.Product;
import me.tabak.fragmentswitcher.FragmentSwitcher;
/**
* TODO: add comment
*/
public interface IFragmentSwitchable {
FragmentViewPager getFragmentSwitcher();
void switchToProductEditor(long productId);
void switchToTagEditor(long tagId);
void switchToTagList();
void switchToProductList(boolean reload, boolean isSelectionMode);
void switchToCalculator(Product product);
}
| Working on Dashboard
| app/src/main/java/io/github/xiaolei/transaction/ui/IFragmentSwitchable.java | Working on Dashboard | <ide><path>pp/src/main/java/io/github/xiaolei/transaction/ui/IFragmentSwitchable.java
<ide>
<ide> import io.github.xiaolei.enterpriselibrary.widget.FragmentViewPager;
<ide> import io.github.xiaolei.transaction.entity.Product;
<del>import me.tabak.fragmentswitcher.FragmentSwitcher;
<ide>
<ide> /**
<ide> * TODO: add comment |
|
Java | apache-2.0 | ca0fd81d3478b4bf843a30bceb5cf1453e51a527 | 0 | ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE | package uk.ac.ebi.quickgo.client.service.loader.presets.withFrom;
import uk.ac.ebi.quickgo.client.model.presets.PresetItem;
import uk.ac.ebi.quickgo.client.model.presets.PresetType;
import uk.ac.ebi.quickgo.client.model.presets.impl.CompositePresetImpl;
import uk.ac.ebi.quickgo.client.service.loader.presets.LogStepListener;
import uk.ac.ebi.quickgo.client.service.loader.presets.PresetsCommonConfig;
import uk.ac.ebi.quickgo.client.service.loader.presets.ff.*;
import uk.ac.ebi.quickgo.rest.search.RetrievalException;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.config.FilterConfigRetrieval;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;
import uk.ac.ebi.quickgo.rest.search.request.converter.RESTFilterConverterFactory;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.Resource;
import org.springframework.web.client.RestOperations;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfig.SKIP_LIMIT;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.compositeItemProcessor;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.fileReader;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.rawPresetMultiFileReader;
import static uk.ac.ebi.quickgo.client.service.loader.presets.ff.SourceColumnsFactory.Source.DB_COLUMNS;
/**
* Exposes the {@link Step} bean that is used to read and populate information relating to the with/from preset data.
*
* Created 01/09/16
* @author Edd
*/
@Configuration
@Import({PresetsCommonConfig.class})
public class WithFromPresetsConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(WithFromPresetsConfig.class);
public static final String WITH_FROM_DB_LOADING_STEP_NAME = "WithFromDBReadingStep";
public static final String WITH_FROM_REST_KEY = "withFrom";
@Value("#{'${withfrom.db.preset.source:}'.split(',')}")
private Resource[] resources;
@Value("${withfrom.db.preset.header.lines:1}")
private int headerLines;
private Set<String> duplicatePrevent = new HashSet<>();
@Bean
public Step withFromDbStep(
StepBuilderFactory stepBuilderFactory,
Integer chunkSize,
CompositePresetImpl presets,
FilterConfigRetrieval externalFilterConfigRetrieval,
RestOperations restOperations) {
RESTFilterConverterFactory converterFactory = converterFactory(externalFilterConfigRetrieval,
restOperations);
FlatFileItemReader<RawNamedPreset> itemReader = fileReader(rawPresetFieldSetMapper());
itemReader.setLinesToSkip(headerLines);
return stepBuilderFactory.get(WITH_FROM_DB_LOADING_STEP_NAME)
.<RawNamedPreset, RawNamedPreset>chunk(chunkSize)
.faultTolerant()
.skipLimit(SKIP_LIMIT)
.<RawNamedPreset>reader(rawPresetMultiFileReader(resources, itemReader))
.processor(compositeItemProcessor(
new RawNamedPresetValidator(),
filterUsingRestResults(converterFactory),
duplicateChecker()))
.writer(rawPresetWriter(presets))
.listener(new LogStepListener())
.build();
}
private RESTFilterConverterFactory converterFactory(FilterConfigRetrieval filterConfigRetrieval,
RestOperations restOperations) {
return new RESTFilterConverterFactory(filterConfigRetrieval, restOperations);
}
/**
* Write the list of {@link RawNamedPreset}s to the {@link CompositePresetImpl}
* @param presets the presets to write to
* @return the corresponding {@link ItemWriter}
*/
private ItemWriter<RawNamedPreset> rawPresetWriter(CompositePresetImpl presets) {
return rawItemList -> rawItemList.forEach(rawItem ->
presets.addPreset(PresetType.WITH_FROM,
PresetItem.createWithName(rawItem.name)
.withProperty(PresetItem.Property.DESCRIPTION.getKey(), rawItem.description)
.withRelevancy(rawItem.relevancy)
.build())
);
}
private FieldSetMapper<RawNamedPreset> rawPresetFieldSetMapper() {
return new StringToRawNamedPresetMapper(SourceColumnsFactory.createFor(DB_COLUMNS));
}
ItemProcessor<RawNamedPreset, RawNamedPreset> duplicateChecker() {
return rawNamedPreset -> duplicatePrevent.add(rawNamedPreset.name.toLowerCase()) ? rawNamedPreset : null;
}
private ItemProcessor<RawNamedPreset, RawNamedPreset> filterUsingRestResults(
RESTFilterConverterFactory converterFactory) {
FilterRequest restRequest = FilterRequest.newBuilder().addProperty(WITH_FROM_REST_KEY).build();
try {
ConvertedFilter<List<String>> convertedFilter = converterFactory.convert(restRequest);
final List<String> convertedValues = convertedFilter.getConvertedValue();
final Set<String> validValues = new HashSet<>(convertedValues);
return rawNamedPreset -> validValues.contains(rawNamedPreset.name) ? rawNamedPreset : null;
} catch (RetrievalException | IllegalStateException e) {
LOGGER.error("Failed to retrieve via REST call the relevant 'with/from' values: ", e);
}
return rawNamedPreset -> rawNamedPreset;
}
}
| quickgo-client/src/main/java/uk/ac/ebi/quickgo/client/service/loader/presets/withFrom/WithFromPresetsConfig.java | package uk.ac.ebi.quickgo.client.service.loader.presets.withFrom;
import uk.ac.ebi.quickgo.client.model.presets.PresetItem;
import uk.ac.ebi.quickgo.client.model.presets.impl.CompositePresetImpl;
import uk.ac.ebi.quickgo.client.service.loader.presets.LogStepListener;
import uk.ac.ebi.quickgo.client.service.loader.presets.PresetsCommonConfig;
import uk.ac.ebi.quickgo.client.service.loader.presets.ff.RawNamedPreset;
import uk.ac.ebi.quickgo.rest.search.request.converter.RESTFilterConverterFactory;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static uk.ac.ebi.quickgo.client.model.presets.PresetType.*;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfig.SKIP_LIMIT;
import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.topItemsFromRESTReader;
/**
* Exposes the {@link Step} bean that is used to read and populate information relating to the with/from preset data.
*
* Created 01/09/16
* @author Edd
*/
@Configuration
@Import({PresetsCommonConfig.class})
public class WithFromPresetsConfig {
public static final String WITH_FROM_DB_LOADING_STEP_NAME = "WithFromDBReadingStep";
public static final String WITH_FROM_REST_KEY = "withFrom";
@Bean
public Step withFromStep(
StepBuilderFactory stepBuilderFactory,
Integer chunkSize,
CompositePresetImpl presets,
RESTFilterConverterFactory converterFactory) {
return stepBuilderFactory.get(WITH_FROM_DB_LOADING_STEP_NAME)
.<RawNamedPreset, RawNamedPreset>chunk(chunkSize)
.faultTolerant()
.skipLimit(SKIP_LIMIT)
.reader(topItemsFromRESTReader(converterFactory, WITH_FROM_REST_KEY))
.writer(rawPresetWriter(presets))
.listener(new LogStepListener())
.build();
}
/**
* Write the list of {@link RawNamedPreset}s to the {@link CompositePresetImpl}
* @param presets the presets to write to
* @return the corresponding {@link ItemWriter}
*/
ItemWriter<RawNamedPreset> rawPresetWriter(CompositePresetImpl presets) {
return rawItemList -> rawItemList.forEach(rawItem -> {
presets.addPreset(WITH_FROM,
PresetItem.createWithName(rawItem.name)
.withRelevancy(rawItem.relevancy)
.build());
});
}
}
| Since we need the descriptions from file, read the file first and then filter by facet of the rest results.
| quickgo-client/src/main/java/uk/ac/ebi/quickgo/client/service/loader/presets/withFrom/WithFromPresetsConfig.java | Since we need the descriptions from file, read the file first and then filter by facet of the rest results. | <ide><path>uickgo-client/src/main/java/uk/ac/ebi/quickgo/client/service/loader/presets/withFrom/WithFromPresetsConfig.java
<ide> package uk.ac.ebi.quickgo.client.service.loader.presets.withFrom;
<ide>
<ide> import uk.ac.ebi.quickgo.client.model.presets.PresetItem;
<add>import uk.ac.ebi.quickgo.client.model.presets.PresetType;
<ide> import uk.ac.ebi.quickgo.client.model.presets.impl.CompositePresetImpl;
<ide> import uk.ac.ebi.quickgo.client.service.loader.presets.LogStepListener;
<ide> import uk.ac.ebi.quickgo.client.service.loader.presets.PresetsCommonConfig;
<del>import uk.ac.ebi.quickgo.client.service.loader.presets.ff.RawNamedPreset;
<add>import uk.ac.ebi.quickgo.client.service.loader.presets.ff.*;
<add>import uk.ac.ebi.quickgo.rest.search.RetrievalException;
<add>import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
<add>import uk.ac.ebi.quickgo.rest.search.request.config.FilterConfigRetrieval;
<add>import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;
<ide> import uk.ac.ebi.quickgo.rest.search.request.converter.RESTFilterConverterFactory;
<ide>
<add>import java.util.HashSet;
<add>import java.util.List;
<add>import java.util.Set;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide> import org.springframework.batch.core.Step;
<ide> import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
<add>import org.springframework.batch.item.ItemProcessor;
<ide> import org.springframework.batch.item.ItemWriter;
<add>import org.springframework.batch.item.file.FlatFileItemReader;
<add>import org.springframework.batch.item.file.mapping.FieldSetMapper;
<add>import org.springframework.beans.factory.annotation.Value;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.context.annotation.Import;
<add>import org.springframework.core.io.Resource;
<add>import org.springframework.web.client.RestOperations;
<ide>
<del>import static uk.ac.ebi.quickgo.client.model.presets.PresetType.*;
<ide> import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfig.SKIP_LIMIT;
<del>import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.topItemsFromRESTReader;
<add>import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.compositeItemProcessor;
<add>import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.fileReader;
<add>import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsConfigHelper.rawPresetMultiFileReader;
<add>import static uk.ac.ebi.quickgo.client.service.loader.presets.ff.SourceColumnsFactory.Source.DB_COLUMNS;
<ide>
<ide> /**
<ide> * Exposes the {@link Step} bean that is used to read and populate information relating to the with/from preset data.
<ide> @Configuration
<ide> @Import({PresetsCommonConfig.class})
<ide> public class WithFromPresetsConfig {
<add> private static final Logger LOGGER = LoggerFactory.getLogger(WithFromPresetsConfig.class);
<add>
<ide> public static final String WITH_FROM_DB_LOADING_STEP_NAME = "WithFromDBReadingStep";
<ide> public static final String WITH_FROM_REST_KEY = "withFrom";
<ide>
<add> @Value("#{'${withfrom.db.preset.source:}'.split(',')}")
<add> private Resource[] resources;
<add> @Value("${withfrom.db.preset.header.lines:1}")
<add> private int headerLines;
<add> private Set<String> duplicatePrevent = new HashSet<>();
<add>
<ide> @Bean
<del> public Step withFromStep(
<add> public Step withFromDbStep(
<ide> StepBuilderFactory stepBuilderFactory,
<ide> Integer chunkSize,
<ide> CompositePresetImpl presets,
<del> RESTFilterConverterFactory converterFactory) {
<add> FilterConfigRetrieval externalFilterConfigRetrieval,
<add> RestOperations restOperations) {
<add>
<add> RESTFilterConverterFactory converterFactory = converterFactory(externalFilterConfigRetrieval,
<add> restOperations);
<add>
<add> FlatFileItemReader<RawNamedPreset> itemReader = fileReader(rawPresetFieldSetMapper());
<add> itemReader.setLinesToSkip(headerLines);
<ide>
<ide> return stepBuilderFactory.get(WITH_FROM_DB_LOADING_STEP_NAME)
<ide> .<RawNamedPreset, RawNamedPreset>chunk(chunkSize)
<ide> .faultTolerant()
<ide> .skipLimit(SKIP_LIMIT)
<del> .reader(topItemsFromRESTReader(converterFactory, WITH_FROM_REST_KEY))
<add> .<RawNamedPreset>reader(rawPresetMultiFileReader(resources, itemReader))
<add> .processor(compositeItemProcessor(
<add> new RawNamedPresetValidator(),
<add> filterUsingRestResults(converterFactory),
<add> duplicateChecker()))
<ide> .writer(rawPresetWriter(presets))
<ide> .listener(new LogStepListener())
<ide> .build();
<add> }
<add>
<add> private RESTFilterConverterFactory converterFactory(FilterConfigRetrieval filterConfigRetrieval,
<add> RestOperations restOperations) {
<add> return new RESTFilterConverterFactory(filterConfigRetrieval, restOperations);
<ide> }
<ide>
<ide> /**
<ide> * @param presets the presets to write to
<ide> * @return the corresponding {@link ItemWriter}
<ide> */
<del> ItemWriter<RawNamedPreset> rawPresetWriter(CompositePresetImpl presets) {
<del> return rawItemList -> rawItemList.forEach(rawItem -> {
<del> presets.addPreset(WITH_FROM,
<del> PresetItem.createWithName(rawItem.name)
<del> .withRelevancy(rawItem.relevancy)
<del> .build());
<del> });
<add> private ItemWriter<RawNamedPreset> rawPresetWriter(CompositePresetImpl presets) {
<add> return rawItemList -> rawItemList.forEach(rawItem ->
<add> presets.addPreset(PresetType.WITH_FROM,
<add> PresetItem.createWithName(rawItem.name)
<add> .withProperty(PresetItem.Property.DESCRIPTION.getKey(), rawItem.description)
<add> .withRelevancy(rawItem.relevancy)
<add> .build())
<add> );
<add> }
<add>
<add> private FieldSetMapper<RawNamedPreset> rawPresetFieldSetMapper() {
<add> return new StringToRawNamedPresetMapper(SourceColumnsFactory.createFor(DB_COLUMNS));
<add> }
<add>
<add> ItemProcessor<RawNamedPreset, RawNamedPreset> duplicateChecker() {
<add> return rawNamedPreset -> duplicatePrevent.add(rawNamedPreset.name.toLowerCase()) ? rawNamedPreset : null;
<add> }
<add>
<add> private ItemProcessor<RawNamedPreset, RawNamedPreset> filterUsingRestResults(
<add> RESTFilterConverterFactory converterFactory) {
<add> FilterRequest restRequest = FilterRequest.newBuilder().addProperty(WITH_FROM_REST_KEY).build();
<add>
<add> try {
<add> ConvertedFilter<List<String>> convertedFilter = converterFactory.convert(restRequest);
<add> final List<String> convertedValues = convertedFilter.getConvertedValue();
<add> final Set<String> validValues = new HashSet<>(convertedValues);
<add> return rawNamedPreset -> validValues.contains(rawNamedPreset.name) ? rawNamedPreset : null;
<add> } catch (RetrievalException | IllegalStateException e) {
<add> LOGGER.error("Failed to retrieve via REST call the relevant 'with/from' values: ", e);
<add> }
<add> return rawNamedPreset -> rawNamedPreset;
<ide> }
<ide> } |
|
Java | apache-2.0 | 0bda826746dd6e70ee5cca1fe9c235b310a6187f | 0 | plusonelabs/calendar-widget,walles/calendar-widget,plusonelabs/calendar-widget,HossainKhademian/CalendarWidget,yvolk/calendar-widget | package com.plusonelabs.calendar.calendar;
import org.joda.time.DateTime;
import org.joda.time.Days;
import com.plusonelabs.calendar.model.Event;
public class CalendarEvent extends Event {
private int eventId;
private String title;
private DateTime endDate;
private int color;
private boolean allDay;
private boolean alarmActive;
private boolean recurring;
private boolean spansMultipleDays;
private CalendarEvent originalEvent;
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public DateTime getEndDate() {
return endDate;
}
public void setEndDate(DateTime endDate) {
this.endDate = endDate;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public boolean isAllDay() {
return allDay;
}
public void setAllDay(boolean allDay) {
this.allDay = allDay;
}
public void setAlarmActive(boolean active) {
this.alarmActive = active;
}
public boolean isAlarmActive() {
return alarmActive;
}
public void setRecurring(boolean recurring) {
this.recurring = recurring;
}
public boolean isRecurring() {
return recurring;
}
public boolean isPartOfMultiDayEvent() {
return spansMultipleDays;
}
public void setSpansMultipleDays(boolean spansMultipleDays) {
this.spansMultipleDays = spansMultipleDays;
}
public int daysSpanned() {
int days = Days.daysBetween(getStartDate().toDateMidnight(), getEndDate().toDateMidnight())
.getDays();
if (!isAllDay()) {
days++;
}
return days;
}
public boolean spansOneFullDay() {
return getStartDate().plusDays(1).isEqual(endDate);
}
public void setOriginalEvent(CalendarEvent originalEvent) {
this.originalEvent = originalEvent;
}
public CalendarEvent getOriginalEvent() {
return originalEvent;
}
public int compareTo(CalendarEvent otherEntry) {
if (isSameDay(otherEntry.getStartDate())) {
if (allDay) {
return -1;
} else if (otherEntry.allDay) {
return 1;
}
}
return super.compareTo(otherEntry);
}
@Override
protected CalendarEvent clone() {
CalendarEvent clone = new CalendarEvent();
clone.setStartDate(getStartDate());
clone.endDate = endDate;
clone.eventId = eventId;
clone.title = title;
clone.allDay = allDay;
clone.color = color;
clone.alarmActive = alarmActive;
clone.recurring = recurring;
clone.spansMultipleDays = spansMultipleDays;
return clone;
}
@Override
public String toString() {
return "CalendarEntry [eventId=" + eventId + ", title=" + title + ", endDate=" + endDate
+ ", color=" + color + ", allDay=" + allDay + ", alarmActive=" + alarmActive
+ ", recurring=" + recurring + ", spansMultipleDays=" + spansMultipleDays
+ ", getStartDate()=" + getStartDate() + "]";
}
}
| app/com.plusonelabs.calendar/src/com/plusonelabs/calendar/calendar/CalendarEvent.java | package com.plusonelabs.calendar.calendar;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.Duration;
import com.plusonelabs.calendar.model.Event;
public class CalendarEvent extends Event {
private int eventId;
private String title;
private DateTime endDate;
private int color;
private boolean allDay;
private boolean alarmActive;
private boolean recurring;
private boolean spansMultipleDays;
private CalendarEvent originalEvent;
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public DateTime getEndDate() {
return endDate;
}
public void setEndDate(DateTime endDate) {
this.endDate = endDate;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public boolean isAllDay() {
return allDay;
}
public void setAllDay(boolean allDay) {
this.allDay = allDay;
}
public void setAlarmActive(boolean active) {
this.alarmActive = active;
}
public boolean isAlarmActive() {
return alarmActive;
}
public void setRecurring(boolean recurring) {
this.recurring = recurring;
}
public boolean isRecurring() {
return recurring;
}
public boolean isPartOfMultiDayEvent() {
return spansMultipleDays;
}
public void setSpansMultipleDays(boolean spansMultipleDays) {
this.spansMultipleDays = spansMultipleDays;
}
public int daysSpanned() {
long durationInMillis = new Duration(getStartDate(), getEndDate()).getMillis();
return (int) Math.ceil(durationInMillis / (double) DateTimeConstants.MILLIS_PER_DAY);
}
public boolean spansOneFullDay() {
return getStartDate().plusDays(1).isEqual(endDate);
}
public void setOriginalEvent(CalendarEvent originalEvent) {
this.originalEvent = originalEvent;
}
public CalendarEvent getOriginalEvent() {
return originalEvent;
}
public int compareTo(CalendarEvent otherEntry) {
if (isSameDay(otherEntry.getStartDate())) {
if (allDay) {
return -1;
} else if (otherEntry.allDay) {
return 1;
}
}
return super.compareTo(otherEntry);
}
@Override
protected CalendarEvent clone() {
CalendarEvent clone = new CalendarEvent();
clone.setStartDate(getStartDate());
clone.endDate = endDate;
clone.eventId = eventId;
clone.title = title;
clone.allDay = allDay;
clone.color = color;
clone.alarmActive = alarmActive;
clone.recurring = recurring;
clone.spansMultipleDays = spansMultipleDays;
return clone;
}
@Override
public String toString() {
return "CalendarEntry [eventId=" + eventId + ", title=" + title + ", endDate=" + endDate
+ ", color=" + color + ", allDay=" + allDay + ", alarmActive=" + alarmActive
+ ", recurring=" + recurring + ", spansMultipleDays=" + spansMultipleDays
+ ", getStartDate()=" + getStartDate() + "]";
}
}
| #47 Fixed duration of events spanning more than one day. | app/com.plusonelabs.calendar/src/com/plusonelabs/calendar/calendar/CalendarEvent.java | #47 Fixed duration of events spanning more than one day. | <ide><path>pp/com.plusonelabs.calendar/src/com/plusonelabs/calendar/calendar/CalendarEvent.java
<ide> package com.plusonelabs.calendar.calendar;
<ide>
<ide> import org.joda.time.DateTime;
<del>import org.joda.time.DateTimeConstants;
<del>import org.joda.time.Duration;
<add>import org.joda.time.Days;
<ide>
<ide> import com.plusonelabs.calendar.model.Event;
<ide>
<ide> }
<ide>
<ide> public int daysSpanned() {
<del> long durationInMillis = new Duration(getStartDate(), getEndDate()).getMillis();
<del> return (int) Math.ceil(durationInMillis / (double) DateTimeConstants.MILLIS_PER_DAY);
<add> int days = Days.daysBetween(getStartDate().toDateMidnight(), getEndDate().toDateMidnight())
<add> .getDays();
<add> if (!isAllDay()) {
<add> days++;
<add> }
<add> return days;
<ide> }
<ide>
<ide> public boolean spansOneFullDay() { |
|
Java | bsd-3-clause | bb8629abe8eeabf66a0ea4d976bca406a628d887 | 0 | 439teamwork/k-9,dhootha/k-9,WenduanMou1/k-9,GuillaumeSmaha/k-9,leixinstar/k-9,moparisthebest/k-9,CodingRmy/k-9,leixinstar/k-9,k9mail/k-9,KitAway/k-9,cooperpellaton/k-9,bashrc/k-9,crr0004/k-9,konfer/k-9,rollbrettler/k-9,sanderbaas/k-9,rtreffer/openpgp-k-9,moparisthebest/k-9,gnebsy/k-9,cooperpellaton/k-9,icedman21/k-9,denim2x/k-9,G00fY2/k-9_material_design,tonytamsf/k-9,cliniome/pki,sonork/k-9,XiveZ/k-9,deepworks/k-9,k9mail/k-9,herpiko/k-9,mawiegand/k-9,msdgwzhy6/k-9,torte71/k-9,philipwhiuk/q-mail,torte71/k-9,gaionim/k-9,msdgwzhy6/k-9,jberkel/k-9,leixinstar/k-9,farmboy0/k-9,nilsbraden/k-9,konfer/k-9,sebkur/k-9,dpereira411/k-9,KitAway/k-9,icedman21/k-9,WenduanMou1/k-9,gnebsy/k-9,cliniome/pki,crr0004/k-9,vatsalsura/k-9,gilbertw1/k-9,dgger/k-9,farmboy0/k-9,denim2x/k-9,GuillaumeSmaha/k-9,sanderbaas/k-9,tsunli/k-9,deepworks/k-9,torte71/k-9,suzp1984/k-9,philipwhiuk/q-mail,bashrc/k-9,439teamwork/k-9,Valodim/k-9,cooperpellaton/k-9,gilbertw1/k-9,msdgwzhy6/k-9,sedrubal/k-9,dgger/k-9,rtreffer/openpgp-k-9,mawiegand/k-9,moparisthebest/k-9,Eagles2F/k-9,cketti/k-9,bashrc/k-9,jberkel/k-9,thuanpq/k-9,suzp1984/k-9,sebkur/k-9,indus1/k-9,Eagles2F/k-9,philipwhiuk/k-9,vt0r/k-9,imaeses/k-9,github201407/k-9,vasyl-khomko/k-9,vasyl-khomko/k-9,GuillaumeSmaha/k-9,vasyl-khomko/k-9,roscrazy/k-9,Eagles2F/k-9,sebkur/k-9,gilbertw1/k-9,sedrubal/k-9,cketti/k-9,huhu/k-9,dpereira411/k-9,gaionim/k-9,crr0004/k-9,cketti/k-9,k9mail/k-9,imaeses/k-9,sonork/k-9,gnebsy/k-9,tsunli/k-9,vatsalsura/k-9,sonork/k-9,CodingRmy/k-9,thuanpq/k-9,WenduanMou1/k-9,farmboy0/k-9,dgger/k-9,denim2x/k-9,tonytamsf/k-9,rollbrettler/k-9,ndew623/k-9,konfer/k-9,mawiegand/k-9,roscrazy/k-9,G00fY2/k-9_material_design,indus1/k-9,suzp1984/k-9,nilsbraden/k-9,jca02266/k-9,ndew623/k-9,KitAway/k-9,ndew623/k-9,imaeses/k-9,dhootha/k-9,jca02266/k-9,icedman21/k-9,dhootha/k-9,rishabhbitsg/k-9,rishabhbitsg/k-9,rollbrettler/k-9,439teamwork/k-9,jca02266/k-9,herpiko/k-9,github201407/k-9,XiveZ/k-9,deepworks/k-9,gaionim/k-9,github201407/k-9,cketti/k-9,philipwhiuk/q-mail,nilsbraden/k-9,XiveZ/k-9,herpiko/k-9,tonytamsf/k-9,dpereira411/k-9,sanderbaas/k-9,cliniome/pki,tsunli/k-9,huhu/k-9,huhu/k-9,philipwhiuk/k-9,thuanpq/k-9,vt0r/k-9 |
package com.android.email.mail.store;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import android.content.SharedPreferences;
import org.apache.commons.io.IOUtils;
import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import android.text.util.Regex;
import android.text.util.Linkify;
import android.text.Spannable;
import android.text.SpannableString;
import com.android.email.Email;
import com.android.email.Preferences;
import com.android.email.Utility;
import com.android.email.codec.binary.Base64OutputStream;
import com.android.email.mail.Address;
import com.android.email.mail.Body;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessageRetrievalListener;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.Store;
import com.android.email.mail.Folder.FolderClass;
import com.android.email.mail.Message.RecipientType;
import com.android.email.mail.internet.MimeBodyPart;
import com.android.email.mail.internet.MimeHeader;
import com.android.email.mail.internet.MimeMessage;
import com.android.email.mail.internet.MimeMultipart;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.mail.internet.TextBody;
import com.android.email.provider.AttachmentProvider;
import java.io.StringReader;
/**
* <pre>
* Implements a SQLite database backed local store for Messages.
* </pre>
*/
public class LocalStore extends Store implements Serializable {
// If you are going to change the DB_VERSION, please also go into Email.java and local for the comment
// on LOCAL_UID_PREFIX and follow the instructions there. If you follow the instructions there,
// please delete this comment.
private static final int DB_VERSION = 24;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN };
private String mPath;
private SQLiteDatabase mDb;
private File mAttachmentsDir;
private Application mApplication;
private String uUid = null;
/**
* @param uri local://localhost/path/to/database/uuid.db
*/
public LocalStore(String _uri, Application application) throws MessagingException {
mApplication = application;
URI uri = null;
try {
uri = new URI(_uri);
} catch (Exception e) {
throw new MessagingException("Invalid uri for LocalStore");
}
if (!uri.getScheme().equals("local")) {
throw new MessagingException("Invalid scheme");
}
mPath = uri.getPath();
// We need to associate the localstore with the account. Since we don't have the account
// handy here, we'll take the filename from the DB and use the basename of the filename
// Folders probably should have references to their containing accounts
File dbFile = new File(mPath);
String[] tokens = dbFile.getName().split("\\.");
uUid = tokens[0];
File parentDir = new File(mPath).getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
mAttachmentsDir = new File(mPath + "_att");
if (!mAttachmentsDir.exists()) {
mAttachmentsDir.mkdirs();
}
mDb = SQLiteDatabase.openOrCreateDatabase(mPath, null);
if (mDb.getVersion() != DB_VERSION) {
doDbUpgrade(mDb, application);
}
}
private void doDbUpgrade ( SQLiteDatabase mDb, Application application) {
Log.i(Email.LOG_TAG, String.format("Upgrading database from version %d to version %d",
mDb.getVersion(), DB_VERSION));
AttachmentProvider.clear(application);
mDb.execSQL("DROP TABLE IF EXISTS folders");
mDb.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, "
+ "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)");
mDb.execSQL("DROP TABLE IF EXISTS messages");
mDb.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, folder_id INTEGER, uid TEXT, subject TEXT, "
+ "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, "
+ "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id ON messages (folder_id)");
mDb.execSQL("DROP TABLE IF EXISTS attachments");
mDb.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER,"
+ "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT,"
+ "mime_type TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS pending_commands");
mDb.execSQL("CREATE TABLE pending_commands " +
"(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_folder");
mDb.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_message");
mDb.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; END;");
mDb.setVersion(DB_VERSION);
if (mDb.getVersion() != DB_VERSION) {
throw new Error("Database upgrade failed!");
}
try
{
pruneCachedAttachments(true);
}
catch (Exception me)
{
Log.e(Email.LOG_TAG, "Exception while force pruning attachments during DB update", me);
}
}
public long getSize()
{
long attachmentLength = 0;
File[] files = mAttachmentsDir.listFiles();
for (File file : files) {
if (file.exists()) {
attachmentLength += file.length();
}
}
File dbFile = new File(mPath);
return dbFile.length() + attachmentLength;
}
public void compact() throws MessagingException
{
Log.i(Email.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments();
Log.i(Email.LOG_TAG, "After prune / before compaction size = " + getSize());
mDb.execSQL("VACUUM");
Log.i(Email.LOG_TAG, "After compaction size = " + getSize());
}
public void clear() throws MessagingException
{
Log.i(Email.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments(true);
Log.i(Email.LOG_TAG, "After prune / before compaction size = " + getSize());
Log.i(Email.LOG_TAG, "Before clear folder count = " + getFolderCount());
Log.i(Email.LOG_TAG, "Before clear message count = " + getMessageCount());
Log.i(Email.LOG_TAG, "After prune / before clear size = " + getSize());
// don't delete messages that are Local, since there is no copy on the server.
// Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have
// been deleted locally. They take up no space, and are indicated with a null date.
mDb.execSQL("DELETE FROM messages WHERE date is not null and uid not like 'Local%'" );
compact();
Log.i(Email.LOG_TAG, "After clear message count = " + getMessageCount());
Log.i(Email.LOG_TAG, "After clear size = " + getSize());
}
public int getMessageCount() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public int getFolderCount() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM folders", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public LocalFolder getFolder(String name) throws MessagingException {
return new LocalFolder(name);
}
// TODO this takes about 260-300ms, seems slow.
@Override
public LocalFolder[] getPersonalNamespaces() throws MessagingException {
ArrayList<LocalFolder> folders = new ArrayList<LocalFolder>();
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT name, id, unread_count, visible_limit, last_updated, status FROM folders", null);
while (cursor.moveToNext()) {
LocalFolder folder = new LocalFolder(cursor.getString(0));
folder.open(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5));
folders.add(folder);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
return folders.toArray(new LocalFolder[] {});
}
@Override
public void checkSettings() throws MessagingException {
}
/**
* Delete the entire Store and it's backing database.
*/
public void delete() {
try {
mDb.close();
} catch (Exception e) {
}
try{
File[] attachments = mAttachmentsDir.listFiles();
for (File attachment : attachments) {
if (attachment.exists()) {
attachment.delete();
}
}
if (mAttachmentsDir.exists()) {
mAttachmentsDir.delete();
}
}
catch (Exception e) {
}
try {
new File(mPath).delete();
}
catch (Exception e) {
}
}
public void pruneCachedAttachments() throws MessagingException {
pruneCachedAttachments(false);
}
/**
* Deletes all cached attachments for the entire store.
*/
public void pruneCachedAttachments(boolean force) throws MessagingException {
if (force)
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, null, null);
}
File[] files = mAttachmentsDir.listFiles();
for (File file : files) {
if (file.exists()) {
if (!force) {
Cursor cursor = null;
try {
cursor = mDb.query(
"attachments",
new String[] { "store_data" },
"id = ?",
new String[] { file.getName() },
null,
null,
null);
if (cursor.moveToNext()) {
if (cursor.getString(0) == null) {
Log.d(Email.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting");
/*
* If the attachment has no store data it is not recoverable, so
* we won't delete it.
*/
continue;
}
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
if (!force)
{
try
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, "id = ?", new String[] { file.getName() });
}
catch (Exception e) {
/*
* If the row has gone away before we got to mark it not-downloaded that's
* okay.
*/
}
}
Log.d(Email.LOG_TAG, "Deleting attachment " + file.getAbsolutePath() + ", which is of size " + file.length());
if (!file.delete()) {
file.deleteOnExit();
}
}
}
}
public void resetVisibleLimits() {
resetVisibleLimits(Email.DEFAULT_VISIBLE_LIMIT);
}
public void resetVisibleLimits(int visibleLimit) {
ContentValues cv = new ContentValues();
cv.put("visible_limit", Integer.toString(visibleLimit));
mDb.update("folders", cv, null, null);
}
public ArrayList<PendingCommand> getPendingCommands() {
Cursor cursor = null;
try {
cursor = mDb.query("pending_commands",
new String[] { "id", "command", "arguments" },
null,
null,
null,
null,
"id ASC");
ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>();
while (cursor.moveToNext()) {
PendingCommand command = new PendingCommand();
command.mId = cursor.getLong(0);
command.command = cursor.getString(1);
String arguments = cursor.getString(2);
command.arguments = arguments.split(",");
for (int i = 0; i < command.arguments.length; i++) {
command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]);
}
commands.add(command);
}
return commands;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public void addPendingCommand(PendingCommand command) {
try {
for (int i = 0; i < command.arguments.length; i++) {
command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8");
}
ContentValues cv = new ContentValues();
cv.put("command", command.command);
cv.put("arguments", Utility.combine(command.arguments, ','));
mDb.insert("pending_commands", "command", cv);
}
catch (UnsupportedEncodingException usee) {
throw new Error("Aparently UTF-8 has been lost to the annals of history.");
}
}
public void removePendingCommand(PendingCommand command) {
mDb.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) });
}
public void removePendingCommands() {
mDb.delete("pending_commands", null, null);
}
public static class PendingCommand {
private long mId;
public String command;
public String[] arguments;
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(command);
sb.append(": ");
for (String argument : arguments) {
sb.append(" ");
sb.append(argument);
//sb.append("\n");
}
return sb.toString();
}
}
public boolean isMoveCapable() {
return true;
}
public boolean isCopyCapable() {
return true;
}
public class LocalFolder extends Folder implements Serializable {
private String mName;
private long mFolderId = -1;
private int mUnreadMessageCount = -1;
private int mVisibleLimit = -1;
private FolderClass displayClass = FolderClass.NONE;
private FolderClass syncClass = FolderClass.NONE;
private String prefId = null;
public LocalFolder(String name) {
this.mName = name;
if (Email.INBOX.equals(getName()))
{
syncClass = FolderClass.FIRST_CLASS;
}
}
public long getId() {
return mFolderId;
}
@Override
public void open(OpenMode mode) throws MessagingException {
if (isOpen()) {
return;
}
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT id, unread_count, visible_limit, last_updated, status FROM folders "
+ "where folders.name = ?",
new String[] {
mName
});
if (cursor.moveToFirst()) {
int folderId = cursor.getInt(0);
if (folderId > 0)
{
open(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getLong(3), cursor.getString(4));
}
} else {
create(FolderType.HOLDS_MESSAGES);
open(mode);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
private void open(int id, int unreadCount, int visibleLimit, long lastChecked, String status) throws MessagingException
{
mFolderId = id;
mUnreadMessageCount = unreadCount;
mVisibleLimit = visibleLimit;
super.setStatus(status);
// Only want to set the local variable stored in the super class. This class
// does a DB update on setLastChecked
super.setLastChecked(lastChecked);
}
@Override
public boolean isOpen() {
return mFolderId != -1;
}
@Override
public OpenMode getMode() throws MessagingException {
return OpenMode.READ_WRITE;
}
@Override
public String getName() {
return mName;
}
@Override
public boolean exists() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT id FROM folders "
+ "where folders.name = ?", new String[] { this
.getName() });
if (cursor.moveToFirst()) {
int folderId = cursor.getInt(0);
return (folderId > 0) ? true : false;
} else {
return false;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException {
if (exists()) {
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] {
mName,
Email.DEFAULT_VISIBLE_LIMIT
});
return true;
}
public boolean create(FolderType type, int visibleLimit) throws MessagingException {
if (exists()) {
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] {
mName,
visibleLimit
});
return true;
}
@Override
public void close(boolean expunge) throws MessagingException {
if (expunge) {
expunge();
}
mFolderId = -1;
}
@Override
public int getMessageCount() throws MessagingException {
open(OpenMode.READ_WRITE);
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?",
new String[] {
Long.toString(mFolderId)
});
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public int getUnreadMessageCount() throws MessagingException {
open(OpenMode.READ_WRITE);
return mUnreadMessageCount;
}
public void setUnreadMessageCount(int unreadMessageCount) throws MessagingException {
open(OpenMode.READ_WRITE);
mUnreadMessageCount = Math.max(0, unreadMessageCount);
mDb.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?",
new Object[] { mUnreadMessageCount, mFolderId });
}
public void setLastChecked(long lastChecked) throws MessagingException {
open(OpenMode.READ_WRITE);
super.setLastChecked(lastChecked);
mDb.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
public int getVisibleLimit() throws MessagingException {
open(OpenMode.READ_WRITE);
return mVisibleLimit;
}
public void setVisibleLimit(int visibleLimit) throws MessagingException {
open(OpenMode.READ_WRITE);
mVisibleLimit = visibleLimit;
mDb.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?",
new Object[] { mVisibleLimit, mFolderId });
}
public void setStatus(String status) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setStatus(status);
mDb.execSQL("UPDATE folders SET status = ? WHERE id = ?",
new Object[] { status, mFolderId });
}
@Override
public FolderClass getDisplayClass()
{
return displayClass;
}
@Override
public FolderClass getSyncClass()
{
if (FolderClass.NONE == syncClass)
{
return displayClass;
}
else
{
return syncClass;
}
}
public FolderClass getRawSyncClass()
{
return syncClass;
}
public void setDisplayClass(FolderClass displayClass)
{
this.displayClass = displayClass;
}
public void setSyncClass(FolderClass syncClass)
{
this.syncClass = syncClass;
}
private String getPrefId() throws MessagingException
{
open(OpenMode.READ_WRITE);
if (prefId == null)
{
prefId = uUid + "." + mName;
}
return prefId;
}
public void delete(Preferences preferences) throws MessagingException {
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode");
editor.commit();
}
public void save(Preferences preferences) throws MessagingException {
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
if (displayClass == FolderClass.NONE && !Email.INBOX.equals(getName()))
{
editor.remove(id + ".displayMode");
}
else
{
editor.putString(id + ".displayMode", displayClass.name());
}
if (syncClass == FolderClass.NONE && !Email.INBOX.equals(getName()))
{
editor.remove(id + ".syncMode");
}
else
{
editor.putString(id + ".syncMode", syncClass.name());
}
editor.commit();
}
public void refresh(Preferences preferences) throws MessagingException {
String id = getPrefId();
try
{
displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NONE.name()));
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to load displayMode for " + getName(), e);
displayClass = FolderClass.NONE;
}
FolderClass defSyncClass = FolderClass.NONE;
if (Email.INBOX.equals(getName()))
{
defSyncClass = FolderClass.FIRST_CLASS;
}
try
{
syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode",
defSyncClass.name()));
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to load syncMode for " + getName(), e);
syncClass = defSyncClass;
}
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
if (fp.contains(FetchProfile.Item.BODY)) {
for (Message message : messages) {
LocalMessage localMessage = (LocalMessage)message;
Cursor cursor = null;
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
MimeMultipart mp = new MimeMultipart();
mp.setSubType("mixed");
localMessage.setBody(mp);
try {
cursor = mDb.rawQuery("SELECT html_content, text_content FROM messages "
+ "WHERE id = ?",
new String[] { Long.toString(localMessage.mId) });
cursor.moveToNext();
String htmlContent = cursor.getString(0);
String textContent = cursor.getString(1);
if (htmlContent != null) {
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
if (textContent != null) {
TextBody body = new TextBody(textContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
try {
cursor = mDb.query(
"attachments",
new String[] {
"id",
"size",
"name",
"mime_type",
"store_data",
"content_uri" },
"message_id = ?",
new String[] { Long.toString(localMessage.mId) },
null,
null,
null);
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
int size = cursor.getInt(1);
String name = cursor.getString(2);
String type = cursor.getString(3);
String storeData = cursor.getString(4);
String contentUri = cursor.getString(5);
Body body = null;
if (contentUri != null) {
body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication);
}
MimeBodyPart bp = new LocalAttachmentBodyPart(body, id);
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
type,
name));
bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format("attachment;\n filename=\"%s\";\n size=%d",
name,
size));
/*
* HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that
* we can later pull the attachment from the remote store if neccesary.
*/
bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData);
mp.addBodyPart(bp);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
private void populateMessageFromGetMessageCursor(LocalMessage message, Cursor cursor)
throws MessagingException{
message.setSubject(cursor.getString(0) == null ? "" : cursor.getString(0));
Address[] from = Address.unpack(cursor.getString(1));
if (from.length > 0) {
message.setFrom(from[0]);
}
message.setSentDate(new Date(cursor.getLong(2)));
message.setUid(cursor.getString(3));
String flagList = cursor.getString(4);
if (flagList != null && flagList.length() > 0) {
String[] flags = flagList.split(",");
try {
for (String flag : flags) {
message.setFlagInternal(Flag.valueOf(flag.toUpperCase()), true);
}
} catch (Exception e) {
}
}
message.mId = cursor.getLong(5);
message.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6)));
message.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7)));
message.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8)));
message.setReplyTo(Address.unpack(cursor.getString(9)));
message.mAttachmentCount = cursor.getInt(10);
message.setInternalDate(new Date(cursor.getLong(11)));
message.setHeader("Message-ID", cursor.getString(12));
}
@Override
public Message[] getMessages(int start, int end, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
throw new MessagingException(
"LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented");
}
@Override
public Message getMessage(String uid) throws MessagingException {
open(OpenMode.READ_WRITE);
LocalMessage message = new LocalMessage(uid, this);
Cursor cursor = null;
try {
cursor = mDb.rawQuery(
"SELECT subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id "
+ "FROM messages " + "WHERE uid = ? " + "AND folder_id = ?",
new String[] {
message.getUid(), Long.toString(mFolderId)
});
if (!cursor.moveToNext()) {
return null;
}
populateMessageFromGetMessageCursor(message, cursor);
}
finally {
if (cursor != null) {
cursor.close();
}
}
return message;
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Message> messages = new ArrayList<Message>();
Cursor cursor = null;
try {
cursor = mDb.rawQuery(
"SELECT subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id "
+ "FROM messages " + "WHERE folder_id = ?", new String[] {
Long.toString(mFolderId)
});
while (cursor.moveToNext()) {
LocalMessage message = new LocalMessage(null, this);
populateMessageFromGetMessageCursor(message, cursor);
messages.add(message);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
return messages.toArray(new Message[] {});
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
if (uids == null) {
return getMessages(listener);
}
ArrayList<Message> messages = new ArrayList<Message>();
for (String uid : uids) {
messages.add(getMessage(uid));
}
return messages.toArray(new Message[] {});
}
@Override
public void copyMessages(Message[] msgs, Folder folder) throws MessagingException {
if (!(folder instanceof LocalFolder)) {
throw new MessagingException("copyMessages called with incorrect Folder");
}
((LocalFolder) folder).appendMessages(msgs, true);
}
@Override
public void moveMessages(Message[] msgs, Folder destFolder) throws MessagingException {
if (!(destFolder instanceof LocalFolder)) {
throw new MessagingException("copyMessages called with non-LocalFolder");
}
LocalFolder lDestFolder = (LocalFolder)destFolder;
lDestFolder.open(OpenMode.READ_WRITE);
for (Message message : msgs)
{
LocalMessage lMessage = (LocalMessage)message;
if (!message.isSet(Flag.SEEN)) {
if (getUnreadMessageCount() > 0) {
setUnreadMessageCount(getUnreadMessageCount() - 1);
}
lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1);
}
String oldUID = message.getUid();
Log.d(Email.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID "
+ message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName());
message.setUid(Email.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
mDb.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] {
lDestFolder.getId(),
message.getUid(),
lMessage.getId() });
LocalMessage placeHolder = new LocalMessage(oldUID, this);
placeHolder.setFlagInternal(Flag.DELETED, true);
appendMessages(new Message[] { placeHolder });
}
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException {
appendMessages(messages, false);
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*/
public void appendMessages(Message[] messages, boolean copy) throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : messages) {
if (!(message instanceof MimeMessage)) {
throw new Error("LocalStore can only store Messages that extend MimeMessage");
}
String uid = message.getUid();
if (uid == null) {
message.setUid(Email.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
}
else {
/*
* The message may already exist in this Folder, so delete it first.
*/
deleteAttachments(message.getUid());
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?",
new Object[] { mFolderId, message.getUid() });
}
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (Part viewable : viewables) {
try {
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html")) {
sbHtml.append(text);
}
else {
sbText.append(text);
}
} catch (Exception e) {
throw new MessagingException("Unable to get text for message part", e);
}
}
sbHtml = markupContent(sbText,sbHtml);
try {
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
cv.put("subject", message.getSubject());
cv.put("sender_list", Address.pack(message.getFrom()));
cv.put("date", message.getSentDate() == null
? System.currentTimeMillis() : message.getSentDate().getTime());
cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase());
cv.put("folder_id", mFolderId);
cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
cv.put("html_content", sbHtml.length() > 0 ? sbHtml.toString() : null);
cv.put("text_content", sbText.length() > 0 ? sbText.toString() : null);
cv.put("reply_to_list", Address.pack(message.getReplyTo()));
cv.put("attachment_count", attachments.size());
cv.put("internal_date", message.getInternalDate() == null
? System.currentTimeMillis() : message.getInternalDate().getTime());
String[] mHeaders = message.getHeader("Message-ID");
if (mHeaders != null && mHeaders.length > 0)
{
cv.put("message_id", mHeaders[0]);
}
long messageId = mDb.insert("messages", "uid", cv);
for (Part attachment : attachments) {
saveAttachment(messageId, attachment, copy);
}
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
}
}
/**
* Update the given message in the LocalStore without first deleting the existing
* message (contrast with appendMessages). This method is used to store changes
* to the given message while updating attachments and not removing existing
* attachment data.
* TODO In the future this method should be combined with appendMessages since the Message
* contains enough data to decide what to do.
* @param message
* @throws MessagingException
*/
public void updateMessage(LocalMessage message) throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (int i = 0, count = viewables.size(); i < count; i++) {
Part viewable = viewables.get(i);
try {
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html")) {
sbHtml.append(text);
}
else {
sbText.append(text);
}
} catch (Exception e) {
throw new MessagingException("Unable to get text for message part", e);
}
}
sbHtml = markupContent(sbText,sbHtml);
try {
mDb.execSQL("UPDATE messages SET "
+ "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, "
+ "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, "
+ "html_content = ?, text_content = ?, reply_to_list = ?, "
+ "attachment_count = ? WHERE id = ?",
new Object[] {
message.getUid(),
message.getSubject(),
Address.pack(message.getFrom()),
message.getSentDate() == null ? System
.currentTimeMillis() : message.getSentDate()
.getTime(),
Utility.combine(message.getFlags(), ',').toUpperCase(),
mFolderId,
Address.pack(message
.getRecipients(RecipientType.TO)),
Address.pack(message
.getRecipients(RecipientType.CC)),
Address.pack(message
.getRecipients(RecipientType.BCC)),
sbHtml.length() > 0 ? sbHtml.toString() : null,
sbText.length() > 0 ? sbText.toString() : null,
Address.pack(message.getReplyTo()),
attachments.size(),
message.mId
});
for (int i = 0, count = attachments.size(); i < count; i++) {
Part attachment = attachments.get(i);
saveAttachment(message.mId, attachment, false);
}
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
}
/**
* @param messageId
* @param attachment
* @param attachmentId -1 to create a new attachment or >= 0 to update an existing
* @throws IOException
* @throws MessagingException
*/
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew)
throws IOException, MessagingException {
long attachmentId = -1;
Uri contentUri = null;
int size = -1;
File tempAttachmentFile = null;
if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) {
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId();
}
if (attachment.getBody() != null) {
Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody) {
contentUri = ((LocalAttachmentBody) body).getContentUri();
}
else {
/*
* If the attachment has a body we're expected to save it into the local store
* so we copy the data into a cached attachment file.
*/
InputStream in = attachment.getBody().getInputStream();
tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
size = IOUtils.copy(in, out);
in.close();
out.close();
}
}
if (size == -1) {
/*
* If the attachment is not yet downloaded see if we can pull a size
* off the Content-Disposition.
*/
String disposition = attachment.getDisposition();
if (disposition != null) {
String s = MimeUtility.getHeaderParameter(disposition, "size");
if (s != null) {
size = Integer.parseInt(s);
}
}
}
if (size == -1) {
size = 0;
}
String storeData =
Utility.combine(attachment.getHeader(
MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ',');
String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name");
String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition());
if (name == null && contentDisposition != null)
{
name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
}
if (attachmentId == -1) {
ContentValues cv = new ContentValues();
cv.put("message_id", messageId);
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("store_data", storeData);
cv.put("size", size);
cv.put("name", name);
cv.put("mime_type", attachment.getMimeType());
attachmentId = mDb.insert("attachments", "message_id", cv);
}
else {
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("size", size);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (tempAttachmentFile != null) {
File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId));
tempAttachmentFile.renameTo(attachmentFile);
contentUri = AttachmentProvider.getAttachmentUri(
new File(mPath).getName(),
attachmentId);
attachment.setBody(new LocalAttachmentBody(contentUri, mApplication));
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (attachment instanceof LocalAttachmentBodyPart) {
((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId);
}
}
/**
* Changes the stored uid of the given message (using it's internal id as a key) to
* the uid in the message.
* @param message
*/
public void changeUid(LocalMessage message) throws MessagingException {
open(OpenMode.READ_WRITE);
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) });
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : messages) {
message.setFlags(flags, value);
}
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : getMessages(null)) {
message.setFlags(flags, value);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException
{
throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder");
}
@Override
public Message[] expunge() throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Message> expungedMessages = new ArrayList<Message>();
/*
* epunge() doesn't do anything because deleted messages are saved for their uids
* and really, really deleted messages are "Destroyed" and removed immediately.
*/
return expungedMessages.toArray(new Message[] {});
}
public void deleteMessagesOlderThan(long cutoff) throws MessagingException
{
open(OpenMode.READ_ONLY);
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? and date < ?", new Object[] {
Long.toString(mFolderId), new Long(cutoff) } );
}
@Override
public void delete(boolean recurse) throws MessagingException {
// We need to open the folder first to make sure we've got it's id
open(OpenMode.READ_ONLY);
Message[] messages = getMessages(null);
for (Message message : messages) {
deleteAttachments(message.getUid());
}
mDb.execSQL("DELETE FROM folders WHERE id = ?", new Object[] {
Long.toString(mFolderId),
});
}
@Override
public boolean equals(Object o) {
if (o instanceof LocalFolder) {
return ((LocalFolder)o).mName.equals(mName);
}
return super.equals(o);
}
@Override
public Flag[] getPermanentFlags() throws MessagingException {
return PERMANENT_FLAGS;
}
private void deleteAttachments(String uid) throws MessagingException {
open(OpenMode.READ_WRITE);
Cursor messagesCursor = null;
try {
messagesCursor = mDb.query(
"messages",
new String[] { "id" },
"folder_id = ? AND uid = ?",
new String[] { Long.toString(mFolderId), uid },
null,
null,
null);
while (messagesCursor.moveToNext()) {
long messageId = messagesCursor.getLong(0);
Cursor attachmentsCursor = null;
try {
attachmentsCursor = mDb.query(
"attachments",
new String[] { "id" },
"message_id = ?",
new String[] { Long.toString(messageId) },
null,
null,
null);
while (attachmentsCursor.moveToNext()) {
long attachmentId = attachmentsCursor.getLong(0);
try{
File file = new File(mAttachmentsDir, Long.toString(attachmentId));
if (file.exists()) {
file.delete();
}
}
catch (Exception e) {
}
}
}
finally {
if (attachmentsCursor != null) {
attachmentsCursor.close();
}
}
}
}
finally {
if (messagesCursor != null) {
messagesCursor.close();
}
}
}
public StringBuffer markupContent(StringBuffer sbText, StringBuffer sbHtml) {
if (sbText.length() > 0 && sbHtml.length() == 0) {
sbHtml.append(htmlifyString(sbText.toString()));
}
Spannable markup = new SpannableString(sbHtml.toString().replaceAll("cid:", "http://cid/"));
Linkify.addLinks(markup, Linkify.ALL);
StringBuffer sb = new StringBuffer(markup.length());
sb.append(markup.toString());
return sb;
}
public String htmlifyString(String text) {
StringReader reader = new StringReader(text);
StringBuilder buff = new StringBuilder(text.length() + 512);
int c = 0;
try {
while ((c = reader.read()) != -1) {
switch (c) {
case '&':
buff.append("&");
break;
case '<':
buff.append("<");
break;
case '>':
buff.append(">");
break;
case '\r':
break;
case '\n':
buff.append("<br/>");
break;
default:
buff.append((char)c);
}//switch
}
} catch (IOException e) {
//Should never happen
Log.e(Email.LOG_TAG, null, e);
}
text = buff.toString();
Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
StringBuffer sb = new StringBuffer(text.length() + 512);
sb.append("<html><body>");
while (m.find()) {
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
} else {
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
sb.append("</body></html>");
text = sb.toString();
return text;
}
}
public class LocalMessage extends MimeMessage {
private long mId;
private int mAttachmentCount;
LocalMessage(String uid, Folder folder) throws MessagingException {
this.mUid = uid;
this.mFolder = folder;
}
public int getAttachmentCount() {
return mAttachmentCount;
}
public void parse(InputStream in) throws IOException, MessagingException {
super.parse(in);
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
}
public long getId() {
return mId;
}
public void setFlag(Flag flag, boolean set) throws MessagingException {
if (flag == Flag.DELETED && set) {
/*
* If a message is being marked as deleted we want to clear out it's content
* and attachments as well. Delete will not actually remove the row since we need
* to retain the uid for synchronization purposes.
*/
/*
* Delete all of the messages' content to save space.
*/
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL(
"UPDATE messages SET " +
"subject = NULL, " +
"sender_list = NULL, " +
"date = NULL, " +
"to_list = NULL, " +
"cc_list = NULL, " +
"bcc_list = NULL, " +
"html_content = NULL, " +
"text_content = NULL, " +
"reply_to_list = NULL " +
"WHERE id = ?",
new Object[] {
mId
});
/*
* Delete all of the messages' attachments to save space.
*/
// shouldn't the trigger take care of this? -- danapple
mDb.execSQL("DELETE FROM attachments WHERE id = ?",
new Object[] {
mId
});
}
else if (flag == Flag.X_DESTROYED && set) {
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL("DELETE FROM messages WHERE id = ?",
new Object[] { mId });
}
/*
* Update the unread count on the folder.
*/
try {
if (flag == Flag.DELETED || flag == Flag.X_DESTROYED || flag == Flag.SEEN) {
LocalFolder folder = (LocalFolder)mFolder;
if (set && !isSet(Flag.SEEN)) {
folder.setUnreadMessageCount(folder.getUnreadMessageCount() - 1);
}
else if (!set && isSet(Flag.SEEN)) {
folder.setUnreadMessageCount(folder.getUnreadMessageCount() + 1);
}
}
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Unable to update LocalStore unread message count",
me);
throw new RuntimeException(me);
}
super.setFlag(flag, set);
/*
* Set the flags on the message.
*/
mDb.execSQL("UPDATE messages " + "SET flags = ? " + "WHERE id = ?", new Object[] {
Utility.combine(getFlags(), ',').toUpperCase(), mId
});
}
}
public class LocalAttachmentBodyPart extends MimeBodyPart {
private long mAttachmentId = -1;
public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException {
super(body);
mAttachmentId = attachmentId;
}
/**
* Returns the local attachment id of this body, or -1 if it is not stored.
* @return
*/
public long getAttachmentId() {
return mAttachmentId;
}
public void setAttachmentId(long attachmentId) {
mAttachmentId = attachmentId;
}
public String toString() {
return "" + mAttachmentId;
}
}
public static class LocalAttachmentBody implements Body {
private Application mApplication;
private Uri mUri;
public LocalAttachmentBody(Uri uri, Application application) {
mApplication = application;
mUri = uri;
}
public InputStream getInputStream() throws MessagingException {
try {
return mApplication.getContentResolver().openInputStream(mUri);
}
catch (FileNotFoundException fnfe) {
/*
* Since it's completely normal for us to try to serve up attachments that
* have been blown away, we just return an empty stream.
*/
return new ByteArrayInputStream(new byte[0]);
}
catch (IOException ioe) {
throw new MessagingException("Invalid attachment.", ioe);
}
}
public void writeTo(OutputStream out) throws IOException, MessagingException {
InputStream in = getInputStream();
Base64OutputStream base64Out = new Base64OutputStream(out);
IOUtils.copy(in, base64Out);
base64Out.close();
}
public Uri getContentUri() {
return mUri;
}
}
}
| src/com/android/email/mail/store/LocalStore.java |
package com.android.email.mail.store;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import android.content.SharedPreferences;
import org.apache.commons.io.IOUtils;
import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Config;
import android.util.Log;
import android.text.util.Regex;
import android.text.util.Linkify;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import com.android.email.Email;
import com.android.email.Preferences;
import com.android.email.Utility;
import com.android.email.codec.binary.Base64OutputStream;
import com.android.email.mail.Address;
import com.android.email.mail.Body;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessageRetrievalListener;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.Store;
import com.android.email.mail.Folder.FolderClass;
import com.android.email.mail.Message.RecipientType;
import com.android.email.mail.internet.MimeBodyPart;
import com.android.email.mail.internet.MimeHeader;
import com.android.email.mail.internet.MimeMessage;
import com.android.email.mail.internet.MimeMultipart;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.mail.internet.TextBody;
import com.android.email.provider.AttachmentProvider;
/**
* <pre>
* Implements a SQLite database backed local store for Messages.
* </pre>
*/
public class LocalStore extends Store implements Serializable {
// If you are going to change the DB_VERSION, please also go into Email.java and local for the comment
// on LOCAL_UID_PREFIX and follow the instructions there. If you follow the instructions there,
// please delete this comment.
private static final int DB_VERSION = 24;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN };
private String mPath;
private SQLiteDatabase mDb;
private File mAttachmentsDir;
private Application mApplication;
private String uUid = null;
/**
* @param uri local://localhost/path/to/database/uuid.db
*/
public LocalStore(String _uri, Application application) throws MessagingException {
mApplication = application;
URI uri = null;
try {
uri = new URI(_uri);
} catch (Exception e) {
throw new MessagingException("Invalid uri for LocalStore");
}
if (!uri.getScheme().equals("local")) {
throw new MessagingException("Invalid scheme");
}
mPath = uri.getPath();
// We need to associate the localstore with the account. Since we don't have the account
// handy here, we'll take the filename from the DB and use the basename of the filename
// Folders probably should have references to their containing accounts
File dbFile = new File(mPath);
String[] tokens = dbFile.getName().split("\\.");
uUid = tokens[0];
File parentDir = new File(mPath).getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
mAttachmentsDir = new File(mPath + "_att");
if (!mAttachmentsDir.exists()) {
mAttachmentsDir.mkdirs();
}
mDb = SQLiteDatabase.openOrCreateDatabase(mPath, null);
if (mDb.getVersion() != DB_VERSION) {
doDbUpgrade(mDb, application);
}
}
private void doDbUpgrade ( SQLiteDatabase mDb, Application application) {
Log.i(Email.LOG_TAG, String.format("Upgrading database from version %d to version %d",
mDb.getVersion(), DB_VERSION));
AttachmentProvider.clear(application);
mDb.execSQL("DROP TABLE IF EXISTS folders");
mDb.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, "
+ "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)");
mDb.execSQL("DROP TABLE IF EXISTS messages");
mDb.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, folder_id INTEGER, uid TEXT, subject TEXT, "
+ "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, "
+ "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id ON messages (folder_id)");
mDb.execSQL("DROP TABLE IF EXISTS attachments");
mDb.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER,"
+ "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT,"
+ "mime_type TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS pending_commands");
mDb.execSQL("CREATE TABLE pending_commands " +
"(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_folder");
mDb.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_message");
mDb.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; END;");
mDb.setVersion(DB_VERSION);
if (mDb.getVersion() != DB_VERSION) {
throw new Error("Database upgrade failed!");
}
try
{
pruneCachedAttachments(true);
}
catch (Exception me)
{
Log.e(Email.LOG_TAG, "Exception while force pruning attachments during DB update", me);
}
}
public long getSize()
{
long attachmentLength = 0;
File[] files = mAttachmentsDir.listFiles();
for (File file : files) {
if (file.exists()) {
attachmentLength += file.length();
}
}
File dbFile = new File(mPath);
return dbFile.length() + attachmentLength;
}
public void compact() throws MessagingException
{
Log.i(Email.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments();
Log.i(Email.LOG_TAG, "After prune / before compaction size = " + getSize());
mDb.execSQL("VACUUM");
Log.i(Email.LOG_TAG, "After compaction size = " + getSize());
}
public void clear() throws MessagingException
{
Log.i(Email.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments(true);
Log.i(Email.LOG_TAG, "After prune / before compaction size = " + getSize());
Log.i(Email.LOG_TAG, "Before clear folder count = " + getFolderCount());
Log.i(Email.LOG_TAG, "Before clear message count = " + getMessageCount());
Log.i(Email.LOG_TAG, "After prune / before clear size = " + getSize());
// don't delete messages that are Local, since there is no copy on the server.
// Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have
// been deleted locally. They take up no space, and are indicated with a null date.
mDb.execSQL("DELETE FROM messages WHERE date is not null and uid not like 'Local%'" );
compact();
Log.i(Email.LOG_TAG, "After clear message count = " + getMessageCount());
Log.i(Email.LOG_TAG, "After clear size = " + getSize());
}
public int getMessageCount() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public int getFolderCount() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM folders", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public LocalFolder getFolder(String name) throws MessagingException {
return new LocalFolder(name);
}
// TODO this takes about 260-300ms, seems slow.
@Override
public LocalFolder[] getPersonalNamespaces() throws MessagingException {
ArrayList<LocalFolder> folders = new ArrayList<LocalFolder>();
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT name, id, unread_count, visible_limit, last_updated, status FROM folders", null);
while (cursor.moveToNext()) {
LocalFolder folder = new LocalFolder(cursor.getString(0));
folder.open(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5));
folders.add(folder);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
return folders.toArray(new LocalFolder[] {});
}
@Override
public void checkSettings() throws MessagingException {
}
/**
* Delete the entire Store and it's backing database.
*/
public void delete() {
try {
mDb.close();
} catch (Exception e) {
}
try{
File[] attachments = mAttachmentsDir.listFiles();
for (File attachment : attachments) {
if (attachment.exists()) {
attachment.delete();
}
}
if (mAttachmentsDir.exists()) {
mAttachmentsDir.delete();
}
}
catch (Exception e) {
}
try {
new File(mPath).delete();
}
catch (Exception e) {
}
}
public void pruneCachedAttachments() throws MessagingException {
pruneCachedAttachments(false);
}
/**
* Deletes all cached attachments for the entire store.
*/
public void pruneCachedAttachments(boolean force) throws MessagingException {
if (force)
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, null, null);
}
File[] files = mAttachmentsDir.listFiles();
for (File file : files) {
if (file.exists()) {
if (!force) {
Cursor cursor = null;
try {
cursor = mDb.query(
"attachments",
new String[] { "store_data" },
"id = ?",
new String[] { file.getName() },
null,
null,
null);
if (cursor.moveToNext()) {
if (cursor.getString(0) == null) {
Log.d(Email.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting");
/*
* If the attachment has no store data it is not recoverable, so
* we won't delete it.
*/
continue;
}
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
if (!force)
{
try
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, "id = ?", new String[] { file.getName() });
}
catch (Exception e) {
/*
* If the row has gone away before we got to mark it not-downloaded that's
* okay.
*/
}
}
Log.d(Email.LOG_TAG, "Deleting attachment " + file.getAbsolutePath() + ", which is of size " + file.length());
if (!file.delete()) {
file.deleteOnExit();
}
}
}
}
public void resetVisibleLimits() {
resetVisibleLimits(Email.DEFAULT_VISIBLE_LIMIT);
}
public void resetVisibleLimits(int visibleLimit) {
ContentValues cv = new ContentValues();
cv.put("visible_limit", Integer.toString(visibleLimit));
mDb.update("folders", cv, null, null);
}
public ArrayList<PendingCommand> getPendingCommands() {
Cursor cursor = null;
try {
cursor = mDb.query("pending_commands",
new String[] { "id", "command", "arguments" },
null,
null,
null,
null,
"id ASC");
ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>();
while (cursor.moveToNext()) {
PendingCommand command = new PendingCommand();
command.mId = cursor.getLong(0);
command.command = cursor.getString(1);
String arguments = cursor.getString(2);
command.arguments = arguments.split(",");
for (int i = 0; i < command.arguments.length; i++) {
command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]);
}
commands.add(command);
}
return commands;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public void addPendingCommand(PendingCommand command) {
try {
for (int i = 0; i < command.arguments.length; i++) {
command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8");
}
ContentValues cv = new ContentValues();
cv.put("command", command.command);
cv.put("arguments", Utility.combine(command.arguments, ','));
mDb.insert("pending_commands", "command", cv);
}
catch (UnsupportedEncodingException usee) {
throw new Error("Aparently UTF-8 has been lost to the annals of history.");
}
}
public void removePendingCommand(PendingCommand command) {
mDb.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) });
}
public void removePendingCommands() {
mDb.delete("pending_commands", null, null);
}
public static class PendingCommand {
private long mId;
public String command;
public String[] arguments;
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(command);
sb.append(": ");
for (String argument : arguments) {
sb.append(" ");
sb.append(argument);
//sb.append("\n");
}
return sb.toString();
}
}
public boolean isMoveCapable() {
return true;
}
public boolean isCopyCapable() {
return true;
}
public class LocalFolder extends Folder implements Serializable {
private String mName;
private long mFolderId = -1;
private int mUnreadMessageCount = -1;
private int mVisibleLimit = -1;
private FolderClass displayClass = FolderClass.NONE;
private FolderClass syncClass = FolderClass.NONE;
private String prefId = null;
public LocalFolder(String name) {
this.mName = name;
if (Email.INBOX.equals(getName()))
{
syncClass = FolderClass.FIRST_CLASS;
}
}
public long getId() {
return mFolderId;
}
@Override
public void open(OpenMode mode) throws MessagingException {
if (isOpen()) {
return;
}
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT id, unread_count, visible_limit, last_updated, status FROM folders "
+ "where folders.name = ?",
new String[] {
mName
});
if (cursor.moveToFirst()) {
int folderId = cursor.getInt(0);
if (folderId > 0)
{
open(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getLong(3), cursor.getString(4));
}
} else {
create(FolderType.HOLDS_MESSAGES);
open(mode);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
private void open(int id, int unreadCount, int visibleLimit, long lastChecked, String status) throws MessagingException
{
mFolderId = id;
mUnreadMessageCount = unreadCount;
mVisibleLimit = visibleLimit;
super.setStatus(status);
// Only want to set the local variable stored in the super class. This class
// does a DB update on setLastChecked
super.setLastChecked(lastChecked);
}
@Override
public boolean isOpen() {
return mFolderId != -1;
}
@Override
public OpenMode getMode() throws MessagingException {
return OpenMode.READ_WRITE;
}
@Override
public String getName() {
return mName;
}
@Override
public boolean exists() throws MessagingException {
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT id FROM folders "
+ "where folders.name = ?", new String[] { this
.getName() });
if (cursor.moveToFirst()) {
int folderId = cursor.getInt(0);
return (folderId > 0) ? true : false;
} else {
return false;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException {
if (exists()) {
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] {
mName,
Email.DEFAULT_VISIBLE_LIMIT
});
return true;
}
public boolean create(FolderType type, int visibleLimit) throws MessagingException {
if (exists()) {
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] {
mName,
visibleLimit
});
return true;
}
@Override
public void close(boolean expunge) throws MessagingException {
if (expunge) {
expunge();
}
mFolderId = -1;
}
@Override
public int getMessageCount() throws MessagingException {
open(OpenMode.READ_WRITE);
Cursor cursor = null;
try {
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?",
new String[] {
Long.toString(mFolderId)
});
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public int getUnreadMessageCount() throws MessagingException {
open(OpenMode.READ_WRITE);
return mUnreadMessageCount;
}
public void setUnreadMessageCount(int unreadMessageCount) throws MessagingException {
open(OpenMode.READ_WRITE);
mUnreadMessageCount = Math.max(0, unreadMessageCount);
mDb.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?",
new Object[] { mUnreadMessageCount, mFolderId });
}
public void setLastChecked(long lastChecked) throws MessagingException {
open(OpenMode.READ_WRITE);
super.setLastChecked(lastChecked);
mDb.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
public int getVisibleLimit() throws MessagingException {
open(OpenMode.READ_WRITE);
return mVisibleLimit;
}
public void setVisibleLimit(int visibleLimit) throws MessagingException {
open(OpenMode.READ_WRITE);
mVisibleLimit = visibleLimit;
mDb.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?",
new Object[] { mVisibleLimit, mFolderId });
}
public void setStatus(String status) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setStatus(status);
mDb.execSQL("UPDATE folders SET status = ? WHERE id = ?",
new Object[] { status, mFolderId });
}
@Override
public FolderClass getDisplayClass()
{
return displayClass;
}
@Override
public FolderClass getSyncClass()
{
if (FolderClass.NONE == syncClass)
{
return displayClass;
}
else
{
return syncClass;
}
}
public FolderClass getRawSyncClass()
{
return syncClass;
}
public void setDisplayClass(FolderClass displayClass)
{
this.displayClass = displayClass;
}
public void setSyncClass(FolderClass syncClass)
{
this.syncClass = syncClass;
}
private String getPrefId() throws MessagingException
{
open(OpenMode.READ_WRITE);
if (prefId == null)
{
prefId = uUid + "." + mName;
}
return prefId;
}
public void delete(Preferences preferences) throws MessagingException {
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode");
editor.commit();
}
public void save(Preferences preferences) throws MessagingException {
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
if (displayClass == FolderClass.NONE && !Email.INBOX.equals(getName()))
{
editor.remove(id + ".displayMode");
}
else
{
editor.putString(id + ".displayMode", displayClass.name());
}
if (syncClass == FolderClass.NONE && !Email.INBOX.equals(getName()))
{
editor.remove(id + ".syncMode");
}
else
{
editor.putString(id + ".syncMode", syncClass.name());
}
editor.commit();
}
public void refresh(Preferences preferences) throws MessagingException {
String id = getPrefId();
try
{
displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NONE.name()));
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to load displayMode for " + getName(), e);
displayClass = FolderClass.NONE;
}
FolderClass defSyncClass = FolderClass.NONE;
if (Email.INBOX.equals(getName()))
{
defSyncClass = FolderClass.FIRST_CLASS;
}
try
{
syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode",
defSyncClass.name()));
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to load syncMode for " + getName(), e);
syncClass = defSyncClass;
}
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
if (fp.contains(FetchProfile.Item.BODY)) {
for (Message message : messages) {
LocalMessage localMessage = (LocalMessage)message;
Cursor cursor = null;
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
MimeMultipart mp = new MimeMultipart();
mp.setSubType("mixed");
localMessage.setBody(mp);
try {
cursor = mDb.rawQuery("SELECT html_content, text_content FROM messages "
+ "WHERE id = ?",
new String[] { Long.toString(localMessage.mId) });
cursor.moveToNext();
String htmlContent = cursor.getString(0);
String textContent = cursor.getString(1);
if (htmlContent != null) {
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
if (textContent != null) {
TextBody body = new TextBody(textContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
try {
cursor = mDb.query(
"attachments",
new String[] {
"id",
"size",
"name",
"mime_type",
"store_data",
"content_uri" },
"message_id = ?",
new String[] { Long.toString(localMessage.mId) },
null,
null,
null);
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
int size = cursor.getInt(1);
String name = cursor.getString(2);
String type = cursor.getString(3);
String storeData = cursor.getString(4);
String contentUri = cursor.getString(5);
Body body = null;
if (contentUri != null) {
body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication);
}
MimeBodyPart bp = new LocalAttachmentBodyPart(body, id);
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
type,
name));
bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format("attachment;\n filename=\"%s\";\n size=%d",
name,
size));
/*
* HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that
* we can later pull the attachment from the remote store if neccesary.
*/
bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData);
mp.addBodyPart(bp);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
private void populateMessageFromGetMessageCursor(LocalMessage message, Cursor cursor)
throws MessagingException{
message.setSubject(cursor.getString(0) == null ? "" : cursor.getString(0));
Address[] from = Address.unpack(cursor.getString(1));
if (from.length > 0) {
message.setFrom(from[0]);
}
message.setSentDate(new Date(cursor.getLong(2)));
message.setUid(cursor.getString(3));
String flagList = cursor.getString(4);
if (flagList != null && flagList.length() > 0) {
String[] flags = flagList.split(",");
try {
for (String flag : flags) {
message.setFlagInternal(Flag.valueOf(flag.toUpperCase()), true);
}
} catch (Exception e) {
}
}
message.mId = cursor.getLong(5);
message.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6)));
message.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7)));
message.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8)));
message.setReplyTo(Address.unpack(cursor.getString(9)));
message.mAttachmentCount = cursor.getInt(10);
message.setInternalDate(new Date(cursor.getLong(11)));
message.setHeader("Message-ID", cursor.getString(12));
}
@Override
public Message[] getMessages(int start, int end, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
throw new MessagingException(
"LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented");
}
@Override
public Message getMessage(String uid) throws MessagingException {
open(OpenMode.READ_WRITE);
LocalMessage message = new LocalMessage(uid, this);
Cursor cursor = null;
try {
cursor = mDb.rawQuery(
"SELECT subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id "
+ "FROM messages " + "WHERE uid = ? " + "AND folder_id = ?",
new String[] {
message.getUid(), Long.toString(mFolderId)
});
if (!cursor.moveToNext()) {
return null;
}
populateMessageFromGetMessageCursor(message, cursor);
}
finally {
if (cursor != null) {
cursor.close();
}
}
return message;
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Message> messages = new ArrayList<Message>();
Cursor cursor = null;
try {
cursor = mDb.rawQuery(
"SELECT subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id "
+ "FROM messages " + "WHERE folder_id = ?", new String[] {
Long.toString(mFolderId)
});
while (cursor.moveToNext()) {
LocalMessage message = new LocalMessage(null, this);
populateMessageFromGetMessageCursor(message, cursor);
messages.add(message);
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
return messages.toArray(new Message[] {});
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException {
open(OpenMode.READ_WRITE);
if (uids == null) {
return getMessages(listener);
}
ArrayList<Message> messages = new ArrayList<Message>();
for (String uid : uids) {
messages.add(getMessage(uid));
}
return messages.toArray(new Message[] {});
}
@Override
public void copyMessages(Message[] msgs, Folder folder) throws MessagingException {
if (!(folder instanceof LocalFolder)) {
throw new MessagingException("copyMessages called with incorrect Folder");
}
((LocalFolder) folder).appendMessages(msgs, true);
}
@Override
public void moveMessages(Message[] msgs, Folder destFolder) throws MessagingException {
if (!(destFolder instanceof LocalFolder)) {
throw new MessagingException("copyMessages called with non-LocalFolder");
}
LocalFolder lDestFolder = (LocalFolder)destFolder;
lDestFolder.open(OpenMode.READ_WRITE);
for (Message message : msgs)
{
LocalMessage lMessage = (LocalMessage)message;
if (!message.isSet(Flag.SEEN)) {
if (getUnreadMessageCount() > 0) {
setUnreadMessageCount(getUnreadMessageCount() - 1);
}
lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1);
}
String oldUID = message.getUid();
Log.d(Email.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID "
+ message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName());
message.setUid(Email.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
mDb.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] {
lDestFolder.getId(),
message.getUid(),
lMessage.getId() });
LocalMessage placeHolder = new LocalMessage(oldUID, this);
placeHolder.setFlagInternal(Flag.DELETED, true);
appendMessages(new Message[] { placeHolder });
}
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException {
appendMessages(messages, false);
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*/
public void appendMessages(Message[] messages, boolean copy) throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : messages) {
if (!(message instanceof MimeMessage)) {
throw new Error("LocalStore can only store Messages that extend MimeMessage");
}
String uid = message.getUid();
if (uid == null) {
message.setUid(Email.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
}
else {
/*
* The message may already exist in this Folder, so delete it first.
*/
deleteAttachments(message.getUid());
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?",
new Object[] { mFolderId, message.getUid() });
}
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (Part viewable : viewables) {
try {
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html")) {
sbHtml.append(text);
}
else {
sbText.append(text);
}
} catch (Exception e) {
throw new MessagingException("Unable to get text for message part", e);
}
}
sbHtml = markupContent(sbText,sbHtml);
try {
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
cv.put("subject", message.getSubject());
cv.put("sender_list", Address.pack(message.getFrom()));
cv.put("date", message.getSentDate() == null
? System.currentTimeMillis() : message.getSentDate().getTime());
cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase());
cv.put("folder_id", mFolderId);
cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
cv.put("html_content", sbHtml.length() > 0 ? sbHtml.toString() : null);
cv.put("text_content", sbText.length() > 0 ? sbText.toString() : null);
cv.put("reply_to_list", Address.pack(message.getReplyTo()));
cv.put("attachment_count", attachments.size());
cv.put("internal_date", message.getInternalDate() == null
? System.currentTimeMillis() : message.getInternalDate().getTime());
String[] mHeaders = message.getHeader("Message-ID");
if (mHeaders != null && mHeaders.length > 0)
{
cv.put("message_id", mHeaders[0]);
}
long messageId = mDb.insert("messages", "uid", cv);
for (Part attachment : attachments) {
saveAttachment(messageId, attachment, copy);
}
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
}
}
/**
* Update the given message in the LocalStore without first deleting the existing
* message (contrast with appendMessages). This method is used to store changes
* to the given message while updating attachments and not removing existing
* attachment data.
* TODO In the future this method should be combined with appendMessages since the Message
* contains enough data to decide what to do.
* @param message
* @throws MessagingException
*/
public void updateMessage(LocalMessage message) throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (int i = 0, count = viewables.size(); i < count; i++) {
Part viewable = viewables.get(i);
try {
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html")) {
sbHtml.append(text);
}
else {
sbText.append(text);
}
} catch (Exception e) {
throw new MessagingException("Unable to get text for message part", e);
}
}
sbHtml = markupContent(sbText,sbHtml);
try {
mDb.execSQL("UPDATE messages SET "
+ "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, "
+ "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, "
+ "html_content = ?, text_content = ?, reply_to_list = ?, "
+ "attachment_count = ? WHERE id = ?",
new Object[] {
message.getUid(),
message.getSubject(),
Address.pack(message.getFrom()),
message.getSentDate() == null ? System
.currentTimeMillis() : message.getSentDate()
.getTime(),
Utility.combine(message.getFlags(), ',').toUpperCase(),
mFolderId,
Address.pack(message
.getRecipients(RecipientType.TO)),
Address.pack(message
.getRecipients(RecipientType.CC)),
Address.pack(message
.getRecipients(RecipientType.BCC)),
sbHtml.length() > 0 ? sbHtml.toString() : null,
sbText.length() > 0 ? sbText.toString() : null,
Address.pack(message.getReplyTo()),
attachments.size(),
message.mId
});
for (int i = 0, count = attachments.size(); i < count; i++) {
Part attachment = attachments.get(i);
saveAttachment(message.mId, attachment, false);
}
} catch (Exception e) {
throw new MessagingException("Error appending message", e);
}
}
/**
* @param messageId
* @param attachment
* @param attachmentId -1 to create a new attachment or >= 0 to update an existing
* @throws IOException
* @throws MessagingException
*/
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew)
throws IOException, MessagingException {
long attachmentId = -1;
Uri contentUri = null;
int size = -1;
File tempAttachmentFile = null;
if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) {
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId();
}
if (attachment.getBody() != null) {
Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody) {
contentUri = ((LocalAttachmentBody) body).getContentUri();
}
else {
/*
* If the attachment has a body we're expected to save it into the local store
* so we copy the data into a cached attachment file.
*/
InputStream in = attachment.getBody().getInputStream();
tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
size = IOUtils.copy(in, out);
in.close();
out.close();
}
}
if (size == -1) {
/*
* If the attachment is not yet downloaded see if we can pull a size
* off the Content-Disposition.
*/
String disposition = attachment.getDisposition();
if (disposition != null) {
String s = MimeUtility.getHeaderParameter(disposition, "size");
if (s != null) {
size = Integer.parseInt(s);
}
}
}
if (size == -1) {
size = 0;
}
String storeData =
Utility.combine(attachment.getHeader(
MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ',');
String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name");
String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition());
if (name == null && contentDisposition != null)
{
name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
}
if (attachmentId == -1) {
ContentValues cv = new ContentValues();
cv.put("message_id", messageId);
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("store_data", storeData);
cv.put("size", size);
cv.put("name", name);
cv.put("mime_type", attachment.getMimeType());
attachmentId = mDb.insert("attachments", "message_id", cv);
}
else {
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("size", size);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (tempAttachmentFile != null) {
File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId));
tempAttachmentFile.renameTo(attachmentFile);
contentUri = AttachmentProvider.getAttachmentUri(
new File(mPath).getName(),
attachmentId);
attachment.setBody(new LocalAttachmentBody(contentUri, mApplication));
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (attachment instanceof LocalAttachmentBodyPart) {
((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId);
}
}
/**
* Changes the stored uid of the given message (using it's internal id as a key) to
* the uid in the message.
* @param message
*/
public void changeUid(LocalMessage message) throws MessagingException {
open(OpenMode.READ_WRITE);
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) });
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : messages) {
message.setFlags(flags, value);
}
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException {
open(OpenMode.READ_WRITE);
for (Message message : getMessages(null)) {
message.setFlags(flags, value);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException
{
throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder");
}
@Override
public Message[] expunge() throws MessagingException {
open(OpenMode.READ_WRITE);
ArrayList<Message> expungedMessages = new ArrayList<Message>();
/*
* epunge() doesn't do anything because deleted messages are saved for their uids
* and really, really deleted messages are "Destroyed" and removed immediately.
*/
return expungedMessages.toArray(new Message[] {});
}
public void deleteMessagesOlderThan(long cutoff) throws MessagingException
{
open(OpenMode.READ_ONLY);
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? and date < ?", new Object[] {
Long.toString(mFolderId), new Long(cutoff) } );
}
@Override
public void delete(boolean recurse) throws MessagingException {
// We need to open the folder first to make sure we've got it's id
open(OpenMode.READ_ONLY);
Message[] messages = getMessages(null);
for (Message message : messages) {
deleteAttachments(message.getUid());
}
mDb.execSQL("DELETE FROM folders WHERE id = ?", new Object[] {
Long.toString(mFolderId),
});
}
@Override
public boolean equals(Object o) {
if (o instanceof LocalFolder) {
return ((LocalFolder)o).mName.equals(mName);
}
return super.equals(o);
}
@Override
public Flag[] getPermanentFlags() throws MessagingException {
return PERMANENT_FLAGS;
}
private void deleteAttachments(String uid) throws MessagingException {
open(OpenMode.READ_WRITE);
Cursor messagesCursor = null;
try {
messagesCursor = mDb.query(
"messages",
new String[] { "id" },
"folder_id = ? AND uid = ?",
new String[] { Long.toString(mFolderId), uid },
null,
null,
null);
while (messagesCursor.moveToNext()) {
long messageId = messagesCursor.getLong(0);
Cursor attachmentsCursor = null;
try {
attachmentsCursor = mDb.query(
"attachments",
new String[] { "id" },
"message_id = ?",
new String[] { Long.toString(messageId) },
null,
null,
null);
while (attachmentsCursor.moveToNext()) {
long attachmentId = attachmentsCursor.getLong(0);
try{
File file = new File(mAttachmentsDir, Long.toString(attachmentId));
if (file.exists()) {
file.delete();
}
}
catch (Exception e) {
}
}
}
finally {
if (attachmentsCursor != null) {
attachmentsCursor.close();
}
}
}
}
finally {
if (messagesCursor != null) {
messagesCursor.close();
}
}
}
public StringBuffer markupContent(StringBuffer sbText, StringBuffer sbHtml) {
if (sbText.length() > 0 && sbHtml.length() == 0) {
sbHtml.append(htmlifyString(sbText.toString()));
}
Spannable markup = new SpannableString(sbHtml.toString().replaceAll("cid:", "http://cid/"));
Linkify.addLinks(markup, Linkify.ALL);
StringBuffer sb = new StringBuffer(markup.length());
sb.append(markup.toString());
return sb;
}
public String htmlifyString(String text) {
text = text.replaceAll("&", "&");
text = text.replaceAll("<", "<");
text = text.replaceAll(">", ">");
text = text.replaceAll("\r?\n", "<br/>");
Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
StringBuffer sb = new StringBuffer(text.length() + 512);
sb.append("<html><body>");
while (m.find()) {
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
}
else {
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
sb.append("</body></html>");
text = sb.toString();
return text;
}
}
public class LocalMessage extends MimeMessage {
private long mId;
private int mAttachmentCount;
LocalMessage(String uid, Folder folder) throws MessagingException {
this.mUid = uid;
this.mFolder = folder;
}
public int getAttachmentCount() {
return mAttachmentCount;
}
public void parse(InputStream in) throws IOException, MessagingException {
super.parse(in);
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
}
public long getId() {
return mId;
}
public void setFlag(Flag flag, boolean set) throws MessagingException {
if (flag == Flag.DELETED && set) {
/*
* If a message is being marked as deleted we want to clear out it's content
* and attachments as well. Delete will not actually remove the row since we need
* to retain the uid for synchronization purposes.
*/
/*
* Delete all of the messages' content to save space.
*/
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL(
"UPDATE messages SET " +
"subject = NULL, " +
"sender_list = NULL, " +
"date = NULL, " +
"to_list = NULL, " +
"cc_list = NULL, " +
"bcc_list = NULL, " +
"html_content = NULL, " +
"text_content = NULL, " +
"reply_to_list = NULL " +
"WHERE id = ?",
new Object[] {
mId
});
/*
* Delete all of the messages' attachments to save space.
*/
// shouldn't the trigger take care of this? -- danapple
mDb.execSQL("DELETE FROM attachments WHERE id = ?",
new Object[] {
mId
});
}
else if (flag == Flag.X_DESTROYED && set) {
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL("DELETE FROM messages WHERE id = ?",
new Object[] { mId });
}
/*
* Update the unread count on the folder.
*/
try {
if (flag == Flag.DELETED || flag == Flag.X_DESTROYED || flag == Flag.SEEN) {
LocalFolder folder = (LocalFolder)mFolder;
if (set && !isSet(Flag.SEEN)) {
folder.setUnreadMessageCount(folder.getUnreadMessageCount() - 1);
}
else if (!set && isSet(Flag.SEEN)) {
folder.setUnreadMessageCount(folder.getUnreadMessageCount() + 1);
}
}
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Unable to update LocalStore unread message count",
me);
throw new RuntimeException(me);
}
super.setFlag(flag, set);
/*
* Set the flags on the message.
*/
mDb.execSQL("UPDATE messages " + "SET flags = ? " + "WHERE id = ?", new Object[] {
Utility.combine(getFlags(), ',').toUpperCase(), mId
});
}
}
public class LocalAttachmentBodyPart extends MimeBodyPart {
private long mAttachmentId = -1;
public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException {
super(body);
mAttachmentId = attachmentId;
}
/**
* Returns the local attachment id of this body, or -1 if it is not stored.
* @return
*/
public long getAttachmentId() {
return mAttachmentId;
}
public void setAttachmentId(long attachmentId) {
mAttachmentId = attachmentId;
}
public String toString() {
return "" + mAttachmentId;
}
}
public static class LocalAttachmentBody implements Body {
private Application mApplication;
private Uri mUri;
public LocalAttachmentBody(Uri uri, Application application) {
mApplication = application;
mUri = uri;
}
public InputStream getInputStream() throws MessagingException {
try {
return mApplication.getContentResolver().openInputStream(mUri);
}
catch (FileNotFoundException fnfe) {
/*
* Since it's completely normal for us to try to serve up attachments that
* have been blown away, we just return an empty stream.
*/
return new ByteArrayInputStream(new byte[0]);
}
catch (IOException ioe) {
throw new MessagingException("Invalid attachment.", ioe);
}
}
public void writeTo(OutputStream out) throws IOException, MessagingException {
InputStream in = getInputStream();
Base64OutputStream base64Out = new Base64OutputStream(out);
IOUtils.copy(in, base64Out);
base64Out.close();
}
public Uri getContentUri() {
return mUri;
}
}
}
| . Potential fix for issue 404: now doing all HTMLization in one pass to minimize the amount of String objects
| src/com/android/email/mail/store/LocalStore.java | . Potential fix for issue 404: now doing all HTMLization in one pass to minimize the amount of String objects | <ide><path>rc/com/android/email/mail/store/LocalStore.java
<ide> import android.database.Cursor;
<ide> import android.database.sqlite.SQLiteDatabase;
<ide> import android.net.Uri;
<del>import android.util.Config;
<ide> import android.util.Log;
<ide> import android.text.util.Regex;
<ide> import android.text.util.Linkify;
<ide> import android.text.Spannable;
<ide> import android.text.SpannableString;
<del>import android.text.SpannableStringBuilder;
<ide>
<ide> import com.android.email.Email;
<ide> import com.android.email.Preferences;
<ide> import com.android.email.mail.internet.MimeUtility;
<ide> import com.android.email.mail.internet.TextBody;
<ide> import com.android.email.provider.AttachmentProvider;
<add>import java.io.StringReader;
<ide>
<ide> /**
<ide> * <pre>
<ide> }
<ide>
<ide> public String htmlifyString(String text) {
<del> text = text.replaceAll("&", "&");
<del> text = text.replaceAll("<", "<");
<del> text = text.replaceAll(">", ">");
<del> text = text.replaceAll("\r?\n", "<br/>");
<del> Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
<del> StringBuffer sb = new StringBuffer(text.length() + 512);
<del> sb.append("<html><body>");
<del> while (m.find()) {
<del> int start = m.start();
<del> if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
<del> m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
<del> }
<del> else {
<del> m.appendReplacement(sb, "$0");
<del> }
<del> }
<del> m.appendTail(sb);
<del> sb.append("</body></html>");
<del> text = sb.toString();
<add> StringReader reader = new StringReader(text);
<add> StringBuilder buff = new StringBuilder(text.length() + 512);
<add> int c = 0;
<add> try {
<add> while ((c = reader.read()) != -1) {
<add> switch (c) {
<add> case '&':
<add> buff.append("&");
<add> break;
<add> case '<':
<add> buff.append("<");
<add> break;
<add> case '>':
<add> buff.append(">");
<add> break;
<add> case '\r':
<add> break;
<add> case '\n':
<add> buff.append("<br/>");
<add> break;
<add> default:
<add> buff.append((char)c);
<add> }//switch
<add> }
<add> } catch (IOException e) {
<add> //Should never happen
<add> Log.e(Email.LOG_TAG, null, e);
<add> }
<add> text = buff.toString();
<add>
<add> Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
<add> StringBuffer sb = new StringBuffer(text.length() + 512);
<add> sb.append("<html><body>");
<add> while (m.find()) {
<add> int start = m.start();
<add> if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
<add> m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
<add> } else {
<add> m.appendReplacement(sb, "$0");
<add> }
<add> }
<add> m.appendTail(sb);
<add> sb.append("</body></html>");
<add> text = sb.toString();
<ide>
<ide> return text;
<ide> }
<del>
<ide> }
<ide>
<ide> public class LocalMessage extends MimeMessage { |
|
Java | apache-2.0 | 846a1f9f42bc145262ab106e1cb301f45181a237 | 0 | diorcety/intellij-community,jexp/idea2,michaelgallacher/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ryano144/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,signed/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,vladmm/intellij-community,kool79/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,slisson/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,retomerz/intellij-community,retomerz/intellij-community,signed/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,jexp/idea2,alphafoobar/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,adedayo/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,signed/intellij-community,jagguli/intellij-community,slisson/intellij-community,adedayo/intellij-community,blademainer/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,caot/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,ernestp/consulo,apixandru/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,TangHao1987/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,consulo/consulo,blademainer/intellij-community,slisson/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,fnouama/intellij-community,kool79/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,kdwink/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,FHannes/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,signed/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,izonder/intellij-community,youdonghai/intellij-community,samthor/intellij-community,jagguli/intellij-community,consulo/consulo,FHannes/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,holmes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ernestp/consulo,adedayo/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,dslomov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,vladmm/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,allotria/intellij-community,retomerz/intellij-community,dslomov/intellij-community,petteyg/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,supersven/intellij-community,izonder/intellij-community,allotria/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,signed/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,semonte/intellij-community,amith01994/intellij-community,supersven/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,caot/intellij-community,asedunov/intellij-community,asedunov/intellij-community,caot/intellij-community,asedunov/intellij-community,da1z/intellij-community,allotria/intellij-community,slisson/intellij-community,jexp/idea2,ol-loginov/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fnouama/intellij-community,vladmm/intellij-community,fitermay/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,holmes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,jagguli/intellij-community,da1z/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ernestp/consulo,caot/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,blademainer/intellij-community,kool79/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,da1z/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,izonder/intellij-community,robovm/robovm-studio,robovm/robovm-studio,mglukhikh/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,allotria/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,consulo/consulo,vladmm/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,izonder/intellij-community,kool79/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,semonte/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,caot/intellij-community,izonder/intellij-community,da1z/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ryano144/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,holmes/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,da1z/intellij-community,adedayo/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,caot/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,samthor/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,izonder/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,kool79/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,slisson/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,dslomov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,signed/intellij-community,allotria/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,jexp/idea2,kool79/intellij-community,blademainer/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,signed/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,da1z/intellij-community,caot/intellij-community,fnouama/intellij-community,caot/intellij-community,blademainer/intellij-community,jagguli/intellij-community,fnouama/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,semonte/intellij-community,clumsy/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,slisson/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,consulo/consulo,ftomassetti/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,jagguli/intellij-community,slisson/intellij-community,suncycheng/intellij-community,signed/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,samthor/intellij-community,amith01994/intellij-community,kool79/intellij-community,caot/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,vladmm/intellij-community,ibinti/intellij-community,signed/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,dslomov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,allotria/intellij-community,jexp/idea2,pwoodworth/intellij-community,kdwink/intellij-community,robovm/robovm-studio,kdwink/intellij-community,wreckJ/intellij-community,samthor/intellij-community,retomerz/intellij-community,petteyg/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,holmes/intellij-community,kdwink/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,kdwink/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,holmes/intellij-community,blademainer/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,diorcety/intellij-community,supersven/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,vladmm/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,holmes/intellij-community,xfournet/intellij-community,samthor/intellij-community,clumsy/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,izonder/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,signed/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,amith01994/intellij-community,jexp/idea2,fnouama/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,samthor/intellij-community,semonte/intellij-community,vladmm/intellij-community,ernestp/consulo,robovm/robovm-studio,nicolargo/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,semonte/intellij-community,xfournet/intellij-community,amith01994/intellij-community,kool79/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,petteyg/intellij-community,supersven/intellij-community,ibinti/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,robovm/robovm-studio,xfournet/intellij-community,dslomov/intellij-community,kdwink/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,supersven/intellij-community,samthor/intellij-community,asedunov/intellij-community,adedayo/intellij-community,caot/intellij-community,vvv1559/intellij-community,signed/intellij-community,gnuhub/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,holmes/intellij-community,allotria/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,signed/intellij-community,idea4bsd/idea4bsd | /*
* Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved.
*/
package com.intellij.util.xml.highlighting;
import com.intellij.codeInsight.daemon.impl.AnnotationHolderImpl;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.GenericValue;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* User: Sergey.Vasiliev
*/
public class DomElementsHighlightingUtil {
private static final AnnotationHolderImpl EMPTY_ANNOTATION_HOLDER = new AnnotationHolderImpl() {
public boolean add(final Annotation annotation) {
return false;
}
};
public static List<ProblemDescriptor> createProblemDescriptors(final InspectionManager manager, final DomElementProblemDescriptor problemDescriptor) {
final ProblemHighlightType type = getProblemHighlightType(problemDescriptor);
return createProblemDescriptors(problemDescriptor, new Function<Pair<TextRange, PsiElement>, ProblemDescriptor>() {
public ProblemDescriptor fun(final Pair<TextRange, PsiElement> s) {
return manager.createProblemDescriptor(s.second, s.first, problemDescriptor.getDescriptionTemplate(), type, problemDescriptor.getFixes());
}
});
}
private static ProblemHighlightType getProblemHighlightType(final DomElementProblemDescriptor problemDescriptor) {
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
final TextRange range = ((DomElementResolveProblemDescriptor)problemDescriptor).getPsiReference().getRangeInElement();
if (range.getStartOffset() != range.getEndOffset()) {
return ProblemHighlightType.LIKE_UNKNOWN_SYMBOL;
}
}
return ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
}
public static List<Annotation> createAnnotations(final DomElementProblemDescriptor problemDescriptor) {
return createProblemDescriptors(problemDescriptor, new Function<Pair<TextRange, PsiElement>, Annotation>() {
public Annotation fun(final Pair<TextRange, PsiElement> s) {
String text = problemDescriptor.getDescriptionTemplate();
if (StringUtil.isEmpty(text)) text = null;
final HighlightSeverity severity = problemDescriptor.getHighlightSeverity();
final AnnotationHolderImpl holder = EMPTY_ANNOTATION_HOLDER;
TextRange range = s.first;
if (text == null) range = TextRange.from(range.getStartOffset(), 0);
range = range.shiftRight(s.second.getTextRange().getStartOffset());
final Annotation annotation = createAnnotation(severity, holder, range, text);
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
annotation.setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES);
}
return annotation;
}
});
}
private static Annotation createAnnotation(final HighlightSeverity severity, final AnnotationHolderImpl holder, final TextRange range,
final String text) {
if (severity.compareTo(HighlightSeverity.ERROR) >= 0) return holder.createErrorAnnotation(range, text);
if (severity.compareTo(HighlightSeverity.WARNING) >= 0) return holder.createWarningAnnotation(range, text);
if (severity.compareTo(HighlightSeverity.INFO) >= 0) return holder.createInformationAnnotation(range, text);
return holder.createInfoAnnotation(range, text);
}
private static <T> List<T> createProblemDescriptors(final DomElementProblemDescriptor problemDescriptor, final Function<Pair<TextRange, PsiElement>, T> creator) {
final List<T> descritors = new SmartList<T>();
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
final PsiReference reference = ((DomElementResolveProblemDescriptor)problemDescriptor).getPsiReference();
final PsiElement element = reference.getElement();
final TextRange referenceRange = reference.getRangeInElement();
final TextRange errorRange;
if (referenceRange.getStartOffset() == referenceRange.getEndOffset()) {
if (element instanceof XmlAttributeValue) {
errorRange = TextRange.from(referenceRange.getStartOffset() - 1, 2);
}
else {
errorRange = TextRange.from(referenceRange.getStartOffset(), 1);
}
} else {
errorRange = referenceRange;
}
descritors.add(creator.fun(Pair.create(errorRange, element)));
return descritors;
}
final DomElement domElement = problemDescriptor.getDomElement();
final PsiElement psiElement = getPsiElement(domElement);
if (psiElement != null && StringUtil.isNotEmpty(psiElement.getText())) {
if (psiElement instanceof XmlTag) {
final XmlTag tag = (XmlTag)psiElement;
addDescriptionsToTagEnds(tag, descritors, creator);
return descritors;
}
int start = 0;
int length = psiElement.getTextRange().getLength();
if (psiElement instanceof XmlAttributeValue) {
String value = ((XmlAttributeValue)psiElement).getValue();
if (StringUtil.isNotEmpty(value)) {
start = psiElement.getText().indexOf(value);
length = value.length();
}
}
return Arrays.asList(creator.fun(Pair.create(TextRange.from(start, length), psiElement)));
}
final XmlTag tag = getParentXmlTag(domElement);
if (tag != null) {
addDescriptionsToTagEnds(tag, descritors, creator);
}
return descritors;
}
private static <T> void addDescriptionsToTagEnds(final XmlTag tag, final List<T> descritors, Function<Pair<TextRange, PsiElement>, T> creator) {
final ASTNode node = tag.getNode();
assert node != null;
final ASTNode startNode = XmlChildRole.START_TAG_NAME_FINDER.findChild(node);
final int startOffset = tag.getTextRange().getStartOffset();
descritors.add(creator.fun(Pair.create(startNode.getTextRange().shiftRight(-startOffset), (PsiElement)tag)));
}
@Nullable
private static PsiElement getPsiElement(final DomElement domElement) {
if (domElement instanceof GenericAttributeValue) {
final GenericAttributeValue attributeValue = (GenericAttributeValue)domElement;
final XmlAttributeValue value = attributeValue.getXmlAttributeValue();
return value != null && StringUtil.isNotEmpty(value.getText()) ? value : attributeValue.getXmlElement();
}
final XmlTag tag = domElement.getXmlTag();
if (domElement instanceof GenericValue && tag != null) {
final XmlText[] textElements = tag.getValue().getTextElements();
if (textElements.length > 0) {
return textElements[0];
}
}
return tag;
}
@Nullable
private static XmlTag getParentXmlTag(final DomElement domElement) {
DomElement parent = domElement.getParent();
while (parent != null) {
if (parent.getXmlTag() != null) return parent.getXmlTag();
parent = parent.getParent();
}
return null;
}
}
| dom/impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java | /*
* Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved.
*/
package com.intellij.util.xml.highlighting;
import com.intellij.codeInsight.daemon.impl.AnnotationHolderImpl;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.GenericValue;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* User: Sergey.Vasiliev
*/
public class DomElementsHighlightingUtil {
private static final AnnotationHolderImpl EMPTY_ANNOTATION_HOLDER = new AnnotationHolderImpl() {
public boolean add(final Annotation annotation) {
return false;
}
};
public static List<ProblemDescriptor> createProblemDescriptors(final InspectionManager manager, final DomElementProblemDescriptor problemDescriptor) {
final ProblemHighlightType type = getProblemHighlightType(problemDescriptor);
return createProblemDescriptors(problemDescriptor, new Function<Pair<TextRange, PsiElement>, ProblemDescriptor>() {
public ProblemDescriptor fun(final Pair<TextRange, PsiElement> s) {
return manager.createProblemDescriptor(s.second, s.first, problemDescriptor.getDescriptionTemplate(), type, problemDescriptor.getFixes());
}
});
}
private static ProblemHighlightType getProblemHighlightType(final DomElementProblemDescriptor problemDescriptor) {
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
final TextRange range = ((DomElementResolveProblemDescriptor)problemDescriptor).getPsiReference().getRangeInElement();
if (range.getStartOffset() != range.getEndOffset()) {
return ProblemHighlightType.LIKE_UNKNOWN_SYMBOL;
}
}
return ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
}
public static List<Annotation> createAnnotations(final DomElementProblemDescriptor problemDescriptor) {
return createProblemDescriptors(problemDescriptor, new Function<Pair<TextRange, PsiElement>, Annotation>() {
public Annotation fun(final Pair<TextRange, PsiElement> s) {
String text = problemDescriptor.getDescriptionTemplate();
if (StringUtil.isEmpty(text)) text = null;
final HighlightSeverity severity = problemDescriptor.getHighlightSeverity();
final AnnotationHolderImpl holder = EMPTY_ANNOTATION_HOLDER;
TextRange range = s.first;
if (text == null) range = TextRange.from(range.getStartOffset(), 0);
range = range.shiftRight(s.second.getTextRange().getStartOffset());
final Annotation annotation = createAnnotation(severity, holder, range, text);
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
annotation.setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES);
}
return annotation;
}
});
}
private static Annotation createAnnotation(final HighlightSeverity severity, final AnnotationHolderImpl holder, final TextRange range,
final String text) {
if (severity.compareTo(HighlightSeverity.ERROR) >= 0) return holder.createErrorAnnotation(range, text);
if (severity.compareTo(HighlightSeverity.WARNING) >= 0) return holder.createWarningAnnotation(range, text);
if (severity.compareTo(HighlightSeverity.INFO) >= 0) return holder.createInformationAnnotation(range, text);
return holder.createInfoAnnotation(range, text);
}
private static <T> List<T> createProblemDescriptors(final DomElementProblemDescriptor problemDescriptor, final Function<Pair<TextRange, PsiElement>, T> creator) {
final List<T> descritors = new SmartList<T>();
if (problemDescriptor instanceof DomElementResolveProblemDescriptor) {
final PsiReference reference = ((DomElementResolveProblemDescriptor)problemDescriptor).getPsiReference();
final PsiElement element = reference.getElement();
final TextRange referenceRange = reference.getRangeInElement();
final TextRange errorRange;
if (referenceRange.getStartOffset() == referenceRange.getEndOffset()) {
if (element instanceof XmlAttributeValue) {
errorRange = TextRange.from(referenceRange.getStartOffset() - 1, 2);
}
else {
errorRange = TextRange.from(referenceRange.getStartOffset(), 1);
}
} else {
errorRange = referenceRange;
}
descritors.add(creator.fun(Pair.create(errorRange, element)));
return descritors;
}
final DomElement domElement = problemDescriptor.getDomElement();
final PsiElement psiElement = getPsiElement(domElement);
if (psiElement != null && StringUtil.isNotEmpty(psiElement.getText())) {
if (psiElement instanceof XmlTag) {
final XmlTag tag = (XmlTag)psiElement;
addDescriptionsToTagEnds(tag, descritors, creator);
return descritors;
}
int start = 0;
int length = psiElement.getTextRange().getLength();
if (psiElement instanceof XmlAttributeValue) {
String value = ((XmlAttributeValue)psiElement).getValue();
if (StringUtil.isNotEmpty(value)) {
start = psiElement.getText().indexOf(value);
length = value.length();
}
}
return Arrays.asList(creator.fun(Pair.create(TextRange.from(start, length), psiElement)));
}
final XmlTag tag = getParentXmlTag(domElement);
if (tag != null) {
addDescriptionsToTagEnds(tag, descritors, creator);
}
return descritors;
}
private static <T> void addDescriptionsToTagEnds(final XmlTag tag, final List<T> descritors, Function<Pair<TextRange, PsiElement>, T> creator) {
final ASTNode node = tag.getNode();
assert node != null;
final ASTNode startNode = XmlChildRole.START_TAG_NAME_FINDER.findChild(node);
final ASTNode endNode = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(node);
final int startOffset = tag.getTextRange().getStartOffset();
descritors.add(creator.fun(Pair.create(startNode.getTextRange().shiftRight(-startOffset), (PsiElement)tag)));
if (endNode != null && !startNode.equals(endNode)) {
descritors.add(creator.fun(Pair.create(endNode.getTextRange().shiftRight(-startOffset), (PsiElement)tag)));
}
}
@Nullable
private static PsiElement getPsiElement(final DomElement domElement) {
if (domElement instanceof GenericAttributeValue) {
final GenericAttributeValue attributeValue = (GenericAttributeValue)domElement;
final XmlAttributeValue value = attributeValue.getXmlAttributeValue();
return value != null && StringUtil.isNotEmpty(value.getText()) ? value : attributeValue.getXmlElement();
}
final XmlTag tag = domElement.getXmlTag();
if (domElement instanceof GenericValue && tag != null) {
final XmlText[] textElements = tag.getValue().getTextElements();
if (textElements.length > 0) {
return textElements[0];
}
}
return tag;
}
@Nullable
private static XmlTag getParentXmlTag(final DomElement domElement) {
DomElement parent = domElement.getParent();
while (parent != null) {
if (parent.getXmlTag() != null) return parent.getXmlTag();
parent = parent.getParent();
}
return null;
}
}
| tests fixed + duplicated error stripes removed from end of xml tags
| dom/impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java | tests fixed + duplicated error stripes removed from end of xml tags | <ide><path>om/impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java
<ide> final ASTNode node = tag.getNode();
<ide> assert node != null;
<ide> final ASTNode startNode = XmlChildRole.START_TAG_NAME_FINDER.findChild(node);
<del> final ASTNode endNode = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(node);
<ide>
<ide> final int startOffset = tag.getTextRange().getStartOffset();
<ide> descritors.add(creator.fun(Pair.create(startNode.getTextRange().shiftRight(-startOffset), (PsiElement)tag)));
<del>
<del> if (endNode != null && !startNode.equals(endNode)) {
<del> descritors.add(creator.fun(Pair.create(endNode.getTextRange().shiftRight(-startOffset), (PsiElement)tag)));
<del> }
<ide> }
<ide>
<ide> @Nullable |
|
Java | apache-2.0 | 115bfb6a28abc757380dacda190c62f5de9fb6a7 | 0 | pixmob/freemobilenetstat | /*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pixmob.freemobile.netstat.monitor;
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG;
import static org.pixmob.freemobile.netstat.Constants.TAG;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.pixmob.freemobile.netstat.R;
import org.pixmob.freemobile.netstat.provider.NetstatContract.BatteryEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.PhoneEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.ScreenEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.WifiEvents;
import org.pixmob.freemobile.netstat.ui.Netstat;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.IBinder;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;
/**
* This foreground service is monitoring phone state and battery level. A
* notification shows which mobile network is the phone is connected to.
* @author Pixmob
*/
public class MonitorService extends Service {
/**
* Match network types from {@link TelephonyManager} with the corresponding
* string.
*/
private static final SparseIntArray NETWORK_TYPE_STRINGS = new SparseIntArray(
8);
/**
* Special data used for terminating the PendingInsert worker thread.
*/
private static final PendingContent STOP_PENDING_CONTENT_MARKER = new PendingContent(
null, null);
/**
* This intent will open the main UI.
*/
private PendingIntent openUIPendingIntent;
private TelephonyManager tm;
private ConnectivityManager cm;
private BroadcastReceiver screenMonitor;
private PhoneStateListener phoneMonitor;
private BroadcastReceiver connectionMonitor;
private BroadcastReceiver batteryMonitor;
private Boolean lastWifiConnected;
private Boolean lastMobileNetworkConnected;
private String lastMobileOperatorId;
private Integer lastBatteryLevel;
private String mobileOperatorId;
private boolean mobileNetworkConnected;
private int mobileNetworkType;
private BlockingQueue<PendingContent> pendingInsert;
static {
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_EDGE,
R.string.network_type_edge);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_GPRS,
R.string.network_type_gprs);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSDPA,
R.string.network_type_hsdpa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPA,
R.string.network_type_hspa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPAP,
R.string.network_type_hspap);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSUPA,
R.string.network_type_hsupa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UMTS,
R.string.network_type_umts);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UNKNOWN,
R.string.network_type_unknown);
}
@Override
public void onCreate() {
super.onCreate();
// Initialize and start a worker thread for inserting rows into the
// application database.
final Context c = getApplicationContext();
pendingInsert = new ArrayBlockingQueue<PendingContent>(8);
new PendingInsertWorker(c, pendingInsert).start();
// This intent is fired when the application notification is clicked.
openUIPendingIntent = PendingIntent.getActivity(c, 0, new Intent(c,
Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_CANCEL_CURRENT);
// Watch screen light: is the screen on?
screenMonitor = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final boolean screenOn = Intent.ACTION_SCREEN_ON.equals(intent
.getAction());
onScreenUpdated(screenOn);
}
};
final IntentFilter screenIntentFilter = new IntentFilter();
screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenMonitor, screenIntentFilter);
// Watch Wi-Fi connections.
cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
connectionMonitor = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
onConnectivityUpdated();
}
};
final IntentFilter connectionIntentFilter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionMonitor, connectionIntentFilter);
// Watch mobile connections.
phoneMonitor = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
mobileNetworkType = networkType;
updateNotification();
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
mobileNetworkConnected = serviceState.getState() == ServiceState.STATE_IN_SERVICE;
onPhoneStateUpdated();
updateNotification();
}
};
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(phoneMonitor, PhoneStateListener.LISTEN_SERVICE_STATE
| PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
// Watch battery level.
batteryMonitor = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final int level = intent.getIntExtra(
BatteryManager.EXTRA_LEVEL, 0);
final int scale = intent.getIntExtra(
BatteryManager.EXTRA_SCALE, 0);
final int levelPercent = (int) Math.round(level * 100d / scale);
onBatteryUpdated(levelPercent);
}
};
final IntentFilter batteryIntentFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryMonitor, batteryIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
// Tell the PendingInsert worker thread to stop.
try {
pendingInsert.put(STOP_PENDING_CONTENT_MARKER);
} catch (InterruptedException e) {
Log.e(TAG, "Failed to stop PendingInsert worker thread", e);
}
// Stop listening to system events.
unregisterReceiver(screenMonitor);
tm.listen(phoneMonitor, PhoneStateListener.LISTEN_NONE);
tm = null;
unregisterReceiver(connectionMonitor);
cm = null;
unregisterReceiver(batteryMonitor);
// Remove the status bar notification.
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
// Update with current state.
onConnectivityUpdated();
onPhoneStateUpdated();
updateNotification();
return START_STICKY;
}
/**
* Update the status bar notification.
*/
private void updateNotification() {
final MobileOperator mobOp = MobileOperator
.fromString(mobileOperatorId);
if (mobOp == null || !mobileNetworkConnected) {
stopForeground(true);
return;
}
final String contentText = String.format(
getString(R.string.mobile_network_type),
getString(NETWORK_TYPE_STRINGS.get(mobileNetworkType)));
final int iconRes;
final String tickerText;
if (MobileOperator.FREE_MOBILE.equals(mobOp)) {
iconRes = R.drawable.ic_stat_connected_to_free_mobile;
tickerText = String.format(
getString(R.string.stat_connected_to_mobile_network),
getString(R.string.network_free_mobile));
} else {
iconRes = R.drawable.ic_stat_connected_to_orange;
tickerText = String.format(
getString(R.string.stat_connected_to_mobile_network),
getString(R.string.network_orange));
}
final Notification n = new NotificationCompat.Builder(
getApplicationContext()).setSmallIcon(iconRes)
.setTicker(tickerText).setContentText(contentText)
.setContentTitle(tickerText)
.setContentIntent(openUIPendingIntent).getNotification();
startForeground(R.string.stat_connected_to_mobile_network, n);
}
/**
* This method is called when the screen light is updated.
*/
private void onScreenUpdated(boolean screenOn) {
Log.i(TAG, "Screen is " + (screenOn ? "on" : "off"));
final ContentValues cv = new ContentValues(4);
cv.put(ScreenEvents.SCREEN_ON, screenOn ? 1 : 0);
cv.put(ScreenEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(ScreenEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(ScreenEvents.SYNC_STATUS, 0);
if (!pendingInsert.offer(new PendingContent(ScreenEvents.CONTENT_URI,
cv))) {
Log.w(TAG, "Failed to schedule screen event insertion");
}
}
/**
* This method is called when the phone data connectivity is updated.
*/
private void onConnectivityUpdated() {
// Get the Wi-Fi connectivity state.
final NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final boolean wifiNetworkConnected = ni != null && ni.isConnected();
// Prevent duplicated inserts.
if (lastWifiConnected != null
&& lastWifiConnected.booleanValue() == wifiNetworkConnected) {
return;
}
lastWifiConnected = wifiNetworkConnected;
Log.i(TAG, "Wifi state updated: connected=" + wifiNetworkConnected);
final ContentValues cv = new ContentValues(4);
cv.put(WifiEvents.WIFI_CONNECTED, wifiNetworkConnected ? 1 : 0);
cv.put(WifiEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(WifiEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(WifiEvents.SYNC_STATUS, 0);
if (!pendingInsert
.offer(new PendingContent(WifiEvents.CONTENT_URI, cv))) {
Log.w(TAG, "Failed to schedule wifi event insertion");
}
}
/**
* This method is called when the phone service state is updated.
*/
private void onPhoneStateUpdated() {
mobileOperatorId = tm.getNetworkOperator();
if (TextUtils.isEmpty(mobileOperatorId)) {
mobileOperatorId = null;
}
// Prevent duplicated inserts.
if (lastMobileNetworkConnected != null
&& lastMobileOperatorId != null
&& lastMobileNetworkConnected.booleanValue() == mobileNetworkConnected
&& lastMobileOperatorId.equals(mobileOperatorId)) {
return;
}
lastMobileNetworkConnected = mobileNetworkConnected;
lastMobileOperatorId = mobileOperatorId;
Log.i(TAG, "Phone state updated: operator=" + mobileOperatorId
+ "; connected=" + mobileNetworkConnected);
final ContentValues cv = new ContentValues(5);
cv.put(PhoneEvents.MOBILE_CONNECTED, mobileNetworkConnected ? 1 : 0);
cv.put(PhoneEvents.MOBILE_OPERATOR, mobileOperatorId);
cv.put(PhoneEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(PhoneEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(PhoneEvents.SYNC_STATUS, 0);
if (!pendingInsert
.offer(new PendingContent(PhoneEvents.CONTENT_URI, cv))) {
Log.w(TAG, "Failed to schedule phone event insertion");
}
}
/**
* This method is called when the battery level is updated.
*/
private void onBatteryUpdated(int level) {
// Prevent duplicated inserts.
if (lastBatteryLevel != null && lastBatteryLevel.intValue() == level) {
return;
}
lastBatteryLevel = level;
Log.i(TAG, "Baterry level updated: " + level + "%");
final ContentValues cv = new ContentValues(4);
cv.put(BatteryEvents.LEVEL, level);
cv.put(WifiEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(WifiEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(WifiEvents.SYNC_STATUS, 0);
if (!pendingInsert.offer(new PendingContent(BatteryEvents.CONTENT_URI,
cv))) {
Log.w(TAG, "Failed to schedule battery event insertion");
}
}
/**
* Pending database content to insert.
* @author Pixmob
*/
private static class PendingContent {
public final Uri contentUri;
public final ContentValues contentValues;
public PendingContent(final Uri contentUri,
final ContentValues contentValues) {
this.contentUri = contentUri;
this.contentValues = contentValues;
}
}
/**
* This internal thread is responsible for inserting data into the
* application database. This thread will prevent the main loop from being
* used for interacting with the database, which could cause
* "Application Not Responding" dialogs.
*/
private static class PendingInsertWorker extends Thread {
private final Context context;
private final BlockingQueue<PendingContent> pendingInsert;
public PendingInsertWorker(final Context context,
final BlockingQueue<PendingContent> pendingInsert) {
super("FreeMobileNetstat/PendingInsert");
setDaemon(true);
this.context = context;
this.pendingInsert = pendingInsert;
}
@Override
public void run() {
if (DEBUG) {
Log.d(TAG, "PendingInsert worker thread is started");
}
// Set a lower priority to prevent UI from lagging.
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
boolean running = true;
while (running) {
try {
final PendingContent data = pendingInsert.take();
if (STOP_PENDING_CONTENT_MARKER == data) {
running = false;
}
if (DEBUG) {
Log.d(TAG, "Inserting new row to " + data.contentUri);
}
context.getContentResolver().insert(data.contentUri,
data.contentValues);
} catch (InterruptedException e) {
running = false;
} catch (Exception e) {
Log.e(TAG, "Pending insert failed", e);
}
}
if (DEBUG) {
Log.d(TAG, "PendingInsert worker thread is terminated");
}
}
}
}
| src/org/pixmob/freemobile/netstat/monitor/MonitorService.java | /*
* Copyright (C) 2012 Pixmob (http://github.com/pixmob)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pixmob.freemobile.netstat.monitor;
import static org.pixmob.freemobile.netstat.Constants.DEBUG;
import static org.pixmob.freemobile.netstat.Constants.TAG;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.pixmob.freemobile.netstat.R;
import org.pixmob.freemobile.netstat.provider.NetstatContract.BatteryEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.PhoneEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.ScreenEvents;
import org.pixmob.freemobile.netstat.provider.NetstatContract.WifiEvents;
import org.pixmob.freemobile.netstat.ui.Netstat;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.IBinder;
import android.os.Process;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;
/**
* This foreground service is monitoring phone state and battery level. A
* notification shows which mobile network is the phone is connected to.
* @author Pixmob
*/
public class MonitorService extends Service {
/**
* Match network types from {@link TelephonyManager} with the corresponding
* string.
*/
private static final SparseIntArray NETWORK_TYPE_STRINGS = new SparseIntArray(
8);
/**
* Special data used for terminating the PendingInsert worker thread.
*/
private static final PendingContent STOP_PENDING_CONTENT_MARKER = new PendingContent(
null, null);
/**
* This intent will open the main UI.
*/
private PendingIntent openUIPendingIntent;
private TelephonyManager tm;
private ConnectivityManager cm;
private BroadcastReceiver screenMonitor;
private PhoneStateListener phoneMonitor;
private BroadcastReceiver connectionMonitor;
private BroadcastReceiver batteryMonitor;
private Boolean lastWifiConnected;
private Boolean lastMobileNetworkConnected;
private String lastMobileOperatorId;
private Integer lastBatteryLevel;
private String mobileOperatorId;
private boolean mobileNetworkConnected;
private int mobileNetworkType;
private BlockingQueue<PendingContent> pendingInsert;
static {
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_EDGE,
R.string.network_type_edge);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_GPRS,
R.string.network_type_gprs);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSDPA,
R.string.network_type_hsdpa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPA,
R.string.network_type_hspa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPAP,
R.string.network_type_hspap);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSUPA,
R.string.network_type_hsupa);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UMTS,
R.string.network_type_umts);
NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UNKNOWN,
R.string.network_type_unknown);
}
@Override
public void onCreate() {
super.onCreate();
// Initialize and start a worker thread for inserting rows into the
// application database.
final Context c = getApplicationContext();
pendingInsert = new ArrayBlockingQueue<PendingContent>(8);
new PendingInsertWorker(c, pendingInsert).start();
// This intent is fired when the application notification is clicked.
openUIPendingIntent = PendingIntent.getActivity(c, 0, new Intent(c,
Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_CANCEL_CURRENT);
// Watch screen light: is the screen on?
screenMonitor = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final boolean screenOn = Intent.ACTION_SCREEN_ON.equals(intent
.getAction());
onScreenUpdated(screenOn);
}
};
final IntentFilter screenIntentFilter = new IntentFilter();
screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenMonitor, screenIntentFilter);
// Watch Wi-Fi connections.
cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
connectionMonitor = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
onConnectivityUpdated();
}
};
final IntentFilter connectionIntentFilter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionMonitor, connectionIntentFilter);
// Watch mobile connections.
phoneMonitor = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
mobileNetworkType = networkType;
updateNotification();
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
mobileNetworkConnected = serviceState.getState() == ServiceState.STATE_IN_SERVICE;
onPhoneStateUpdated();
updateNotification();
}
};
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(phoneMonitor, PhoneStateListener.LISTEN_SERVICE_STATE
| PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
// Watch battery level.
batteryMonitor = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final int level = intent.getIntExtra(
BatteryManager.EXTRA_LEVEL, 0);
final int scale = intent.getIntExtra(
BatteryManager.EXTRA_SCALE, 0);
final int levelPercent = (int) Math.round(level * 100d / scale);
onBatteryUpdated(levelPercent);
}
};
final IntentFilter batteryIntentFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryMonitor, batteryIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
// Tell the PendingInsert worker thread to stop.
try {
pendingInsert.put(STOP_PENDING_CONTENT_MARKER);
} catch (InterruptedException e) {
Log.e(TAG, "Failed to stop PendingInsert worker thread", e);
}
// Stop listening to system events.
unregisterReceiver(screenMonitor);
tm.listen(phoneMonitor, PhoneStateListener.LISTEN_NONE);
tm = null;
unregisterReceiver(connectionMonitor);
cm = null;
unregisterReceiver(batteryMonitor);
// Remove the status bar notification.
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
// Update with current state.
onConnectivityUpdated();
onPhoneStateUpdated();
updateNotification();
return START_STICKY;
}
/**
* Update the status bar notification.
*/
private void updateNotification() {
final MobileOperator mobOp = MobileOperator
.fromString(mobileOperatorId);
if (mobOp == null || !mobileNetworkConnected) {
stopForeground(true);
return;
}
final String contentText = String.format(
getString(R.string.mobile_network_type),
getString(NETWORK_TYPE_STRINGS.get(mobileNetworkType)));
final int iconRes;
final String tickerText;
if (MobileOperator.FREE_MOBILE.equals(mobOp)) {
iconRes = R.drawable.ic_stat_connected_to_free_mobile;
tickerText = String.format(
getString(R.string.stat_connected_to_mobile_network),
getString(R.string.network_free_mobile));
} else {
iconRes = R.drawable.ic_stat_connected_to_orange;
tickerText = String.format(
getString(R.string.stat_connected_to_mobile_network),
getString(R.string.network_orange));
}
final Notification n = new Notification(iconRes, tickerText, 0);
n.setLatestEventInfo(getApplicationContext(), tickerText, contentText,
openUIPendingIntent);
startForeground(R.string.stat_connected_to_mobile_network, n);
}
/**
* This method is called when the screen light is updated.
*/
private void onScreenUpdated(boolean screenOn) {
Log.i(TAG, "Screen is " + (screenOn ? "on" : "off"));
final ContentValues cv = new ContentValues(4);
cv.put(ScreenEvents.SCREEN_ON, screenOn ? 1 : 0);
cv.put(ScreenEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(ScreenEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(ScreenEvents.SYNC_STATUS, 0);
if (!pendingInsert.offer(new PendingContent(ScreenEvents.CONTENT_URI,
cv))) {
Log.w(TAG, "Failed to schedule screen event insertion");
}
}
/**
* This method is called when the phone data connectivity is updated.
*/
private void onConnectivityUpdated() {
// Get the Wi-Fi connectivity state.
final NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final boolean wifiNetworkConnected = ni != null && ni.isConnected();
// Prevent duplicated inserts.
if (lastWifiConnected != null
&& lastWifiConnected.booleanValue() == wifiNetworkConnected) {
return;
}
lastWifiConnected = wifiNetworkConnected;
Log.i(TAG, "Wifi state updated: connected=" + wifiNetworkConnected);
final ContentValues cv = new ContentValues(4);
cv.put(WifiEvents.WIFI_CONNECTED, wifiNetworkConnected ? 1 : 0);
cv.put(WifiEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(WifiEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(WifiEvents.SYNC_STATUS, 0);
if (!pendingInsert
.offer(new PendingContent(WifiEvents.CONTENT_URI, cv))) {
Log.w(TAG, "Failed to schedule wifi event insertion");
}
}
/**
* This method is called when the phone service state is updated.
*/
private void onPhoneStateUpdated() {
mobileOperatorId = tm.getNetworkOperator();
if (TextUtils.isEmpty(mobileOperatorId)) {
mobileOperatorId = null;
}
// Prevent duplicated inserts.
if (lastMobileNetworkConnected != null
&& lastMobileOperatorId != null
&& lastMobileNetworkConnected.booleanValue() == mobileNetworkConnected
&& lastMobileOperatorId.equals(mobileOperatorId)) {
return;
}
lastMobileNetworkConnected = mobileNetworkConnected;
lastMobileOperatorId = mobileOperatorId;
Log.i(TAG, "Phone state updated: operator=" + mobileOperatorId
+ "; connected=" + mobileNetworkConnected);
final ContentValues cv = new ContentValues(5);
cv.put(PhoneEvents.MOBILE_CONNECTED, mobileNetworkConnected ? 1 : 0);
cv.put(PhoneEvents.MOBILE_OPERATOR, mobileOperatorId);
cv.put(PhoneEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(PhoneEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(PhoneEvents.SYNC_STATUS, 0);
if (!pendingInsert
.offer(new PendingContent(PhoneEvents.CONTENT_URI, cv))) {
Log.w(TAG, "Failed to schedule phone event insertion");
}
}
/**
* This method is called when the battery level is updated.
*/
private void onBatteryUpdated(int level) {
// Prevent duplicated inserts.
if (lastBatteryLevel != null && lastBatteryLevel.intValue() == level) {
return;
}
lastBatteryLevel = level;
Log.i(TAG, "Baterry level updated: " + level + "%");
final ContentValues cv = new ContentValues(4);
cv.put(BatteryEvents.LEVEL, level);
cv.put(WifiEvents.TIMESTAMP, System.currentTimeMillis());
cv.put(WifiEvents.SYNC_ID, UUID.randomUUID().toString());
cv.put(WifiEvents.SYNC_STATUS, 0);
if (!pendingInsert.offer(new PendingContent(BatteryEvents.CONTENT_URI,
cv))) {
Log.w(TAG, "Failed to schedule battery event insertion");
}
}
/**
* Pending database content to insert.
* @author Pixmob
*/
private static class PendingContent {
public final Uri contentUri;
public final ContentValues contentValues;
public PendingContent(final Uri contentUri,
final ContentValues contentValues) {
this.contentUri = contentUri;
this.contentValues = contentValues;
}
}
/**
* This internal thread is responsible for inserting data into the
* application database. This thread will prevent the main loop from being
* used for interacting with the database, which could cause
* "Application Not Responding" dialogs.
*/
private static class PendingInsertWorker extends Thread {
private final Context context;
private final BlockingQueue<PendingContent> pendingInsert;
public PendingInsertWorker(final Context context,
final BlockingQueue<PendingContent> pendingInsert) {
super("FreeMobileNetstat/PendingInsert");
setDaemon(true);
this.context = context;
this.pendingInsert = pendingInsert;
}
@Override
public void run() {
if (DEBUG) {
Log.d(TAG, "PendingInsert worker thread is started");
}
// Set a lower priority to prevent UI from lagging.
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
boolean running = true;
while (running) {
try {
final PendingContent data = pendingInsert.take();
if (STOP_PENDING_CONTENT_MARKER == data) {
running = false;
}
if (DEBUG) {
Log.d(TAG, "Inserting new row to " + data.contentUri);
}
context.getContentResolver().insert(data.contentUri,
data.contentValues);
} catch (InterruptedException e) {
running = false;
} catch (Exception e) {
Log.e(TAG, "Pending insert failed", e);
}
}
if (DEBUG) {
Log.d(TAG, "PendingInsert worker thread is terminated");
}
}
}
}
| Fix deprecation error by using the new support library
The new support library introduced by ADT 17 comes with
the class NotificationCompat.Builder. Using this class
will remove the deprecation error caused by the use of
the older Notification API (SDK < 11).
| src/org/pixmob/freemobile/netstat/monitor/MonitorService.java | Fix deprecation error by using the new support library | <ide><path>rc/org/pixmob/freemobile/netstat/monitor/MonitorService.java
<ide> */
<ide> package org.pixmob.freemobile.netstat.monitor;
<ide>
<del>import static org.pixmob.freemobile.netstat.Constants.DEBUG;
<add>import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG;
<ide> import static org.pixmob.freemobile.netstat.Constants.TAG;
<ide>
<ide> import java.util.UUID;
<ide> import android.os.BatteryManager;
<ide> import android.os.IBinder;
<ide> import android.os.Process;
<add>import android.support.v4.app.NotificationCompat;
<ide> import android.telephony.PhoneStateListener;
<ide> import android.telephony.ServiceState;
<ide> import android.telephony.TelephonyManager;
<ide> getString(R.string.stat_connected_to_mobile_network),
<ide> getString(R.string.network_orange));
<ide> }
<del> final Notification n = new Notification(iconRes, tickerText, 0);
<del> n.setLatestEventInfo(getApplicationContext(), tickerText, contentText,
<del> openUIPendingIntent);
<add> final Notification n = new NotificationCompat.Builder(
<add> getApplicationContext()).setSmallIcon(iconRes)
<add> .setTicker(tickerText).setContentText(contentText)
<add> .setContentTitle(tickerText)
<add> .setContentIntent(openUIPendingIntent).getNotification();
<ide>
<ide> startForeground(R.string.stat_connected_to_mobile_network, n);
<ide> } |
|
Java | apache-2.0 | 681791036c14325bd0fe5aed54b3ae2aff6ba478 | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr | package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsConsumer;
import org.apache.lucene.codecs.TermStats;
import org.apache.lucene.codecs.TermsConsumer;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FlushInfo;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Abstract class to do basic tests for a postings format.
* NOTE: This test focuses on the postings
* (docs/freqs/positions/payloads/offsets) impl, not the
* terms dict. The [stretch] goal is for this test to be
* so thorough in testing a new PostingsFormat that if this
* test passes, then all Lucene/Solr tests should also pass. Ie,
* if there is some bug in a given PostingsFormat that this
* test fails to catch then this test needs to be improved! */
// TODO can we make it easy for testing to pair up a "random terms dict impl" with your postings base format...
// TODO test when you reuse after skipping a term or two, eg the block reuse case
// TODO hmm contract says .doc() can return NO_MORE_DOCS
// before nextDoc too...?
/* TODO
- threads
- assert doc=-1 before any nextDoc
- if a PF passes this test but fails other tests then this
test has a bug!!
- test tricky reuse cases, eg across fields
- verify you get null if you pass needFreq/needOffset but
they weren't indexed
*/
public abstract class BasePostingsFormatTestCase extends LuceneTestCase {
/**
* Returns the Codec to run tests against
*/
protected abstract Codec getCodec();
private enum Option {
// Sometimes use .advance():
SKIPPING,
// Sometimes reuse the Docs/AndPositionsEnum across terms:
REUSE_ENUMS,
// Sometimes pass non-null live docs:
LIVE_DOCS,
// Sometimes seek to term using previously saved TermState:
TERM_STATE,
// Sometimes don't fully consume docs from the enum
PARTIAL_DOC_CONSUME,
// Sometimes don't fully consume positions at each doc
PARTIAL_POS_CONSUME,
// Sometimes check payloads
PAYLOADS,
// Test w/ multiple threads
THREADS};
private static class FieldAndTerm {
String field;
BytesRef term;
public FieldAndTerm(String field, BytesRef term) {
this.field = field;
this.term = BytesRef.deepCopyOf(term);
}
}
private static class Position {
int position;
byte[] payload;
int startOffset;
int endOffset;
}
private static class Posting implements Comparable<Posting> {
int docID;
List<Position> positions;
public int compareTo(Posting other) {
return docID - other.docID;
}
}
// Holds all postings:
private static Map<String,Map<BytesRef,List<Posting>>> fields;
// Holds only live doc postings:
private static Map<String,Map<BytesRef,List<Posting>>> fieldsLive;
private static FieldInfos fieldInfos;
private static int maxDocID;
private static FixedBitSet globalLiveDocs;
private static List<FieldAndTerm> allTerms;
private static long totalPostings;
private static long totalPayloadBytes;
@BeforeClass
public static void createPostings() throws IOException {
fields = new TreeMap<String,Map<BytesRef,List<Posting>>>();
fieldsLive = new TreeMap<String,Map<BytesRef,List<Posting>>>();
final int numFields = _TestUtil.nextInt(random(), 1, 5);
if (VERBOSE) {
System.out.println("TEST: " + numFields + " fields");
}
FieldInfo[] fieldInfoArray = new FieldInfo[numFields];
int fieldUpto = 0;
int numMediumTerms = 0;
int numBigTerms = 0;
int numManyPositions = 0;
totalPostings = 0;
totalPayloadBytes = 0;
while (fieldUpto < numFields) {
String field = _TestUtil.randomSimpleString(random());
if (fields.containsKey(field)) {
continue;
}
fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, true,
IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS,
null, DocValues.Type.FIXED_INTS_8, null);
fieldUpto++;
Map<BytesRef,List<Posting>> postings = new TreeMap<BytesRef,List<Posting>>();
fields.put(field, postings);
Set<String> seenTerms = new HashSet<String>();
final int numTerms = atLeast(10);
for(int termUpto=0;termUpto<numTerms;termUpto++) {
String term = _TestUtil.randomSimpleString(random());
if (seenTerms.contains(term)) {
continue;
}
seenTerms.add(term);
int numDocs;
if (numBigTerms == 0 || (random().nextInt(10) == 3 && numBigTerms < 2)) {
// Make at least 1 big term, then maybe (~10%
// chance) make another:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 50000, 70000);
numBigTerms++;
term = "big_" + term;
} else if (numMediumTerms == 0 || (random().nextInt(10) == 3 && numMediumTerms < 5)) {
// Make at least 1 medium term, then maybe (~10%
// chance) make up to 4 more:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 3000, 6000);
numMediumTerms++;
term = "medium_" + term;
} else if (random().nextBoolean()) {
// Low freq term:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 1, 40);
term = "low_" + term;
} else {
// Very low freq term (don't multiply by RANDOM_MULTIPLIER):
numDocs = _TestUtil.nextInt(random(), 1, 3);
term = "verylow_" + term;
}
List<Posting> termPostings = new ArrayList<Posting>();
postings.put(new BytesRef(term), termPostings);
int docID = 0;
// TODO: more realistic to inversely tie this to numDocs:
int maxDocSpacing = _TestUtil.nextInt(random(), 1, 100);
int payloadSize;
if (random().nextInt(10) == 7) {
// 10% of the time create big payloads:
payloadSize = random().nextInt(50);
} else {
payloadSize = random().nextInt(10);
}
boolean fixedPayloads = random().nextBoolean();
for(int docUpto=0;docUpto<numDocs;docUpto++) {
if (docUpto == 0 && random().nextBoolean()) {
// Sometimes index docID = 0
} else if (maxDocSpacing == 1) {
docID++;
} else {
// TODO: sometimes have a biggish gap here!
docID += _TestUtil.nextInt(random(), 1, maxDocSpacing);
}
Posting posting = new Posting();
posting.docID = docID;
maxDocID = Math.max(docID, maxDocID);
posting.positions = new ArrayList<Position>();
termPostings.add(posting);
int freq;
if (random().nextInt(30) == 17 && numManyPositions < 10) {
freq = _TestUtil.nextInt(random(), 1, 1000);
numManyPositions++;
} else {
freq = _TestUtil.nextInt(random(), 1, 20);
}
int pos = 0;
int offset = 0;
int posSpacing = _TestUtil.nextInt(random(), 1, 100);
totalPostings += freq;
for(int posUpto=0;posUpto<freq;posUpto++) {
if (posUpto == 0 && random().nextBoolean()) {
// Sometimes index pos = 0
} else if (posSpacing == 1) {
pos++;
} else {
pos += _TestUtil.nextInt(random(), 1, posSpacing);
}
Position position = new Position();
posting.positions.add(position);
position.position = pos;
if (payloadSize != 0) {
if (fixedPayloads) {
position.payload = new byte[payloadSize];
} else {
int thisPayloadSize = random().nextInt(payloadSize);
if (thisPayloadSize != 0) {
position.payload = new byte[thisPayloadSize];
}
}
}
if (position.payload != null) {
random().nextBytes(position.payload);
totalPayloadBytes += position.payload.length;
}
position.startOffset = offset + random().nextInt(5);
position.endOffset = position.startOffset + random().nextInt(10);
offset = position.endOffset;
}
}
}
}
fieldInfos = new FieldInfos(fieldInfoArray);
globalLiveDocs = new FixedBitSet(1+maxDocID);
double liveRatio = random().nextDouble();
for(int i=0;i<1+maxDocID;i++) {
if (random().nextDouble() <= liveRatio) {
globalLiveDocs.set(i);
}
}
// Pre-filter postings by globalLiveDocs:
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
Map<BytesRef,List<Posting>> postingsLive = new TreeMap<BytesRef,List<Posting>>();
fieldsLive.put(fieldEnt.getKey(), postingsLive);
for(Map.Entry<BytesRef,List<Posting>> termEnt : fieldEnt.getValue().entrySet()) {
List<Posting> termPostingsLive = new ArrayList<Posting>();
postingsLive.put(termEnt.getKey(), termPostingsLive);
for(Posting posting : termEnt.getValue()) {
if (globalLiveDocs.get(posting.docID)) {
termPostingsLive.add(posting);
}
}
}
}
allTerms = new ArrayList<FieldAndTerm>();
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
String field = fieldEnt.getKey();
for(Map.Entry<BytesRef,List<Posting>> termEnt : fieldEnt.getValue().entrySet()) {
allTerms.add(new FieldAndTerm(field, termEnt.getKey()));
}
}
if (VERBOSE) {
System.out.println("TEST: done init postings; maxDocID=" + maxDocID + "; " + allTerms.size() + " total terms, across " + fieldInfos.size() + " fields");
}
}
@AfterClass
public static void afterClass() throws Exception {
allTerms = null;
fieldInfos = null;
fields = null;
fieldsLive = null;
globalLiveDocs = null;
}
// TODO maybe instead of @BeforeClass just make a single test run: build postings & index & test it?
private FieldInfos currentFieldInfos;
// maxAllowed = the "highest" we can index, but we will still
// randomly index at lower IndexOption
private FieldsProducer buildIndex(Directory dir, IndexOptions maxAllowed, boolean allowPayloads, boolean alwaysTestMax) throws IOException {
Codec codec = getCodec();
SegmentInfo segmentInfo = new SegmentInfo(dir, Constants.LUCENE_MAIN_VERSION, "_0", 1+maxDocID, false, codec, null, null);
int maxIndexOption = Arrays.asList(IndexOptions.values()).indexOf(maxAllowed);
if (VERBOSE) {
System.out.println("\nTEST: now build index");
}
int maxIndexOptionNoOffsets = Arrays.asList(IndexOptions.values()).indexOf(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
// TODO use allowPayloads
FieldInfo[] newFieldInfoArray = new FieldInfo[fields.size()];
for(int fieldUpto=0;fieldUpto<fields.size();fieldUpto++) {
FieldInfo oldFieldInfo = fieldInfos.fieldInfo(fieldUpto);
String pf = _TestUtil.getPostingsFormat(codec, oldFieldInfo.name);
int fieldMaxIndexOption;
if (doesntSupportOffsets.contains(pf)) {
fieldMaxIndexOption = Math.min(maxIndexOptionNoOffsets, maxIndexOption);
} else {
fieldMaxIndexOption = maxIndexOption;
}
// Randomly picked the IndexOptions to index this
// field with:
IndexOptions indexOptions = IndexOptions.values()[alwaysTestMax ? fieldMaxIndexOption : random().nextInt(1+fieldMaxIndexOption)];
boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
newFieldInfoArray[fieldUpto] = new FieldInfo(oldFieldInfo.name,
true,
fieldUpto,
false,
false,
doPayloads,
indexOptions,
null,
DocValues.Type.FIXED_INTS_8,
null);
}
FieldInfos newFieldInfos = new FieldInfos(newFieldInfoArray);
// Estimate that flushed segment size will be 25% of
// what we use in RAM:
long bytes = totalPostings * 8 + totalPayloadBytes;
SegmentWriteState writeState = new SegmentWriteState(null, dir,
segmentInfo, newFieldInfos,
32, null, new IOContext(new FlushInfo(maxDocID, bytes)));
FieldsConsumer fieldsConsumer = codec.postingsFormat().fieldsConsumer(writeState);
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
String field = fieldEnt.getKey();
Map<BytesRef,List<Posting>> terms = fieldEnt.getValue();
FieldInfo fieldInfo = newFieldInfos.fieldInfo(field);
IndexOptions indexOptions = fieldInfo.getIndexOptions();
if (VERBOSE) {
System.out.println("field=" + field + " indexOtions=" + indexOptions);
}
boolean doFreq = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
boolean doPos = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
boolean doOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
TermsConsumer termsConsumer = fieldsConsumer.addField(fieldInfo);
long sumTotalTF = 0;
long sumDF = 0;
FixedBitSet seenDocs = new FixedBitSet(maxDocID+1);
for(Map.Entry<BytesRef,List<Posting>> termEnt : terms.entrySet()) {
BytesRef term = termEnt.getKey();
List<Posting> postings = termEnt.getValue();
if (VERBOSE) {
System.out.println(" term=" + field + ":" + term.utf8ToString() + " docFreq=" + postings.size());
}
PostingsConsumer postingsConsumer = termsConsumer.startTerm(term);
long totalTF = 0;
int docCount = 0;
for(Posting posting : postings) {
if (VERBOSE) {
System.out.println(" " + docCount + ": docID=" + posting.docID + " freq=" + posting.positions.size());
}
postingsConsumer.startDoc(posting.docID, doFreq ? posting.positions.size() : -1);
seenDocs.set(posting.docID);
if (doPos) {
totalTF += posting.positions.size();
for(Position pos : posting.positions) {
if (VERBOSE) {
if (doPayloads) {
System.out.println(" pos=" + pos.position + " payload=" + (pos.payload == null ? "null" : pos.payload.length + " bytes"));
} else {
System.out.println(" pos=" + pos.position);
}
}
postingsConsumer.addPosition(pos.position, (doPayloads && pos.payload != null) ? new BytesRef(pos.payload) : null, doOffsets ? pos.startOffset : -1, doOffsets ? pos.endOffset : -1);
}
} else if (doFreq) {
totalTF += posting.positions.size();
} else {
totalTF++;
}
postingsConsumer.finishDoc();
docCount++;
}
termsConsumer.finishTerm(term, new TermStats(postings.size(), doFreq ? totalTF : -1));
sumTotalTF += totalTF;
sumDF += postings.size();
}
termsConsumer.finish(doFreq ? sumTotalTF : -1, sumDF, seenDocs.cardinality());
}
fieldsConsumer.close();
if (VERBOSE) {
System.out.println("TEST: after indexing: files=");
for(String file : dir.listAll()) {
System.out.println(" " + file + ": " + dir.fileLength(file) + " bytes");
}
}
currentFieldInfos = newFieldInfos;
SegmentReadState readState = new SegmentReadState(dir, segmentInfo, newFieldInfos, IOContext.DEFAULT, 1);
return codec.postingsFormat().fieldsProducer(readState);
}
private static class ThreadState {
// Only used with REUSE option:
public DocsEnum reuseDocsEnum;
public DocsAndPositionsEnum reuseDocsAndPositionsEnum;
}
private void verifyEnum(ThreadState threadState,
String field,
BytesRef term,
TermsEnum termsEnum,
// Maximum options (docs/freqs/positions/offsets) to test:
IndexOptions maxIndexOptions,
EnumSet<Option> options,
boolean alwaysTestMax) throws IOException {
if (VERBOSE) {
System.out.println(" verifyEnum: options=" + options + " maxIndexOptions=" + maxIndexOptions);
}
// 50% of the time time pass liveDocs:
Bits liveDocs;
Map<String,Map<BytesRef,List<Posting>>> fieldsToUse;
if (options.contains(Option.LIVE_DOCS) && random().nextBoolean()) {
liveDocs = globalLiveDocs;
fieldsToUse = fieldsLive;
if (VERBOSE) {
System.out.println(" use liveDocs");
}
} else {
liveDocs = null;
fieldsToUse = fields;
if (VERBOSE) {
System.out.println(" no liveDocs");
}
}
FieldInfo fieldInfo = currentFieldInfos.fieldInfo(field);
assertEquals(fields.get(field).get(term).size(), termsEnum.docFreq());
// NOTE: can be empty list if we are using liveDocs:
List<Posting> expected = fieldsToUse.get(field).get(term);
boolean allowFreqs = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
boolean doCheckFreqs = allowFreqs && (alwaysTestMax || random().nextInt(3) <= 2);
boolean allowPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
boolean doCheckPositions = allowPositions && (alwaysTestMax || random().nextInt(3) <= 2);
boolean allowOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
boolean doCheckOffsets = allowOffsets && (alwaysTestMax || random().nextInt(3) <= 2);
boolean doCheckPayloads = options.contains(Option.PAYLOADS) && allowPositions && fieldInfo.hasPayloads() && (alwaysTestMax || random().nextInt(3) <= 2);
DocsEnum prevDocsEnum = null;
DocsEnum docsEnum;
DocsAndPositionsEnum docsAndPositionsEnum;
if (!doCheckPositions) {
if (allowPositions && random().nextInt(10) == 7) {
// 10% of the time, even though we will not check positions, pull a DocsAndPositions enum
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
}
int flags = 0;
if (alwaysTestMax || random().nextBoolean()) {
flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
}
if (alwaysTestMax || random().nextBoolean()) {
flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
}
if (VERBOSE) {
System.out.println(" get DocsAndPositionsEnum (but we won't check positions) flags=" + flags);
}
threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
docsEnum = threadState.reuseDocsAndPositionsEnum;
docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
} else {
if (VERBOSE) {
System.out.println(" get DocsEnum");
}
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsEnum;
}
threadState.reuseDocsEnum = termsEnum.docs(liveDocs, prevDocsEnum, doCheckFreqs ? DocsEnum.FLAG_FREQS : 0);
docsEnum = threadState.reuseDocsEnum;
docsAndPositionsEnum = null;
}
} else {
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
}
int flags = 0;
if (alwaysTestMax || doCheckOffsets || random().nextInt(3) == 1) {
flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
}
if (alwaysTestMax || doCheckPayloads|| random().nextInt(3) == 1) {
flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
}
if (VERBOSE) {
System.out.println(" get DocsAndPositionsEnum flags=" + flags);
}
threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
docsEnum = threadState.reuseDocsAndPositionsEnum;
docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
}
assertNotNull("null DocsEnum", docsEnum);
int initialDocID = docsEnum.docID();
assertTrue("inital docID should be -1 or NO_MORE_DOCS: " + docsEnum, initialDocID == -1 || initialDocID == DocsEnum.NO_MORE_DOCS);
if (VERBOSE) {
if (prevDocsEnum == null) {
System.out.println(" got enum=" + docsEnum);
} else if (prevDocsEnum == docsEnum) {
System.out.println(" got reuse enum=" + docsEnum);
} else {
System.out.println(" got enum=" + docsEnum + " (reuse of " + prevDocsEnum + " failed)");
}
}
// 10% of the time don't consume all docs:
int stopAt;
if (!alwaysTestMax && options.contains(Option.PARTIAL_DOC_CONSUME) && expected.size() > 1 && random().nextInt(10) == 7) {
stopAt = random().nextInt(expected.size()-1);
if (VERBOSE) {
System.out.println(" will not consume all docs (" + stopAt + " vs " + expected.size() + ")");
}
} else {
stopAt = expected.size();
if (VERBOSE) {
System.out.println(" consume all docs");
}
}
double skipChance = alwaysTestMax ? 0.5 : random().nextDouble();
int numSkips = expected.size() < 3 ? 1 : _TestUtil.nextInt(random(), 1, Math.min(20, expected.size()/3));
int skipInc = expected.size()/numSkips;
int skipDocInc = (1+maxDocID)/numSkips;
// Sometimes do 100% skipping:
boolean doAllSkipping = options.contains(Option.SKIPPING) && random().nextInt(7) == 1;
double freqAskChance = alwaysTestMax ? 1.0 : random().nextDouble();
double payloadCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();
double offsetCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();
if (VERBOSE) {
if (options.contains(Option.SKIPPING)) {
System.out.println(" skipChance=" + skipChance + " numSkips=" + numSkips);
} else {
System.out.println(" no skipping");
}
if (doCheckFreqs) {
System.out.println(" freqAskChance=" + freqAskChance);
}
if (doCheckPayloads) {
System.out.println(" payloadCheckChance=" + payloadCheckChance);
}
if (doCheckOffsets) {
System.out.println(" offsetCheckChance=" + offsetCheckChance);
}
}
int nextPosting = 0;
while (nextPosting <= stopAt) {
if (nextPosting == stopAt) {
if (stopAt == expected.size()) {
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.nextDoc());
// Common bug is to forget to set this.doc=NO_MORE_DOCS in the enum!:
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.docID());
}
break;
}
Posting posting;
if (options.contains(Option.SKIPPING) && (doAllSkipping || random().nextDouble() <= skipChance)) {
int targetDocID = -1;
if (nextPosting < stopAt && random().nextBoolean()) {
// Pick target we know exists:
nextPosting = _TestUtil.nextInt(random(), nextPosting, nextPosting+skipInc);
} else {
// Pick random target (might not exist):
Posting target = new Posting();
target.docID = _TestUtil.nextInt(random(), expected.get(nextPosting).docID, expected.get(nextPosting).docID+skipDocInc);
targetDocID = target.docID;
int loc = Collections.binarySearch(expected.subList(nextPosting, expected.size()), target);
if (loc < 0) {
loc = -loc-1;
}
nextPosting = nextPosting + loc;
}
if (nextPosting >= stopAt) {
int target = random().nextBoolean() ? (maxDocID+1) : DocsEnum.NO_MORE_DOCS;
if (VERBOSE) {
System.out.println(" now advance to end (target=" + target + ")");
}
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.advance(target));
break;
} else {
posting = expected.get(nextPosting++);
if (VERBOSE) {
if (targetDocID != -1) {
System.out.println(" now advance to random target=" + targetDocID + " (" + nextPosting + " of " + stopAt + ")");
} else {
System.out.println(" now advance to known-exists target=" + posting.docID + " (" + nextPosting + " of " + stopAt + ")");
}
}
int docID = docsEnum.advance(targetDocID != -1 ? targetDocID : posting.docID);
assertEquals("docID is wrong", posting.docID, docID);
}
} else {
posting = expected.get(nextPosting++);
if (VERBOSE) {
System.out.println(" now nextDoc to " + posting.docID + " (" + nextPosting + " of " + stopAt + ")");
}
int docID = docsEnum.nextDoc();
assertEquals("docID is wrong", posting.docID, docID);
}
if (doCheckFreqs && random().nextDouble() <= freqAskChance) {
if (VERBOSE) {
System.out.println(" now freq()=" + posting.positions.size());
}
int freq = docsEnum.freq();
assertEquals("freq is wrong", posting.positions.size(), freq);
}
if (doCheckPositions) {
int freq = docsEnum.freq();
int numPosToConsume;
if (!alwaysTestMax && options.contains(Option.PARTIAL_POS_CONSUME) && random().nextInt(5) == 1) {
numPosToConsume = random().nextInt(freq);
} else {
numPosToConsume = freq;
}
for(int i=0;i<numPosToConsume;i++) {
Position position = posting.positions.get(i);
if (VERBOSE) {
System.out.println(" now nextPosition to " + position.position);
}
assertEquals("position is wrong", position.position, docsAndPositionsEnum.nextPosition());
// TODO sometimes don't pull the payload even
// though we pulled the position
if (doCheckPayloads) {
if (random().nextDouble() <= payloadCheckChance) {
if (VERBOSE) {
System.out.println(" now check payload length=" + (position.payload == null ? 0 : position.payload.length));
}
if (position.payload == null || position.payload.length == 0) {
assertNull("should not have payload", docsAndPositionsEnum.getPayload());
} else {
BytesRef payload = docsAndPositionsEnum.getPayload();
assertNotNull("should have payload but doesn't", payload);
assertEquals("payload length is wrong", position.payload.length, payload.length);
for(int byteUpto=0;byteUpto<position.payload.length;byteUpto++) {
assertEquals("payload bytes are wrong",
position.payload[byteUpto],
payload.bytes[payload.offset+byteUpto]);
}
// make a deep copy
payload = BytesRef.deepCopyOf(payload);
assertEquals("2nd call to getPayload returns something different!", payload, docsAndPositionsEnum.getPayload());
}
} else {
if (VERBOSE) {
System.out.println(" skip check payload length=" + (position.payload == null ? 0 : position.payload.length));
}
}
}
if (doCheckOffsets) {
if (random().nextDouble() <= offsetCheckChance) {
if (VERBOSE) {
System.out.println(" now check offsets: startOff=" + position.startOffset + " endOffset=" + position.endOffset);
}
assertEquals("startOffset is wrong", position.startOffset, docsAndPositionsEnum.startOffset());
assertEquals("endOffset is wrong", position.endOffset, docsAndPositionsEnum.endOffset());
} else {
if (VERBOSE) {
System.out.println(" skip check offsets");
}
}
} else if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
if (VERBOSE) {
System.out.println(" now check offsets are -1");
}
assertEquals("startOffset isn't -1", -1, docsAndPositionsEnum.startOffset());
assertEquals("endOffset isn't -1", -1, docsAndPositionsEnum.endOffset());
}
}
}
}
}
private void testTerms(final Fields fieldsSource, final EnumSet<Option> options,
final IndexOptions maxIndexOptions,
final boolean alwaysTestMax) throws Exception {
if (options.contains(Option.THREADS)) {
int numThreads = _TestUtil.nextInt(random(), 2, 5);
Thread[] threads = new Thread[numThreads];
for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
threads[threadUpto] = new Thread() {
@Override
public void run() {
try {
testTermsOneThread(fieldsSource, options, maxIndexOptions, alwaysTestMax);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
};
threads[threadUpto].start();
}
for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
threads[threadUpto].join();
}
} else {
testTermsOneThread(fieldsSource, options, maxIndexOptions, alwaysTestMax);
}
}
private void testTermsOneThread(Fields fieldsSource, EnumSet<Option> options, IndexOptions maxIndexOptions, boolean alwaysTestMax) throws IOException {
ThreadState threadState = new ThreadState();
// Test random terms/fields:
List<TermState> termStates = new ArrayList<TermState>();
List<FieldAndTerm> termStateTerms = new ArrayList<FieldAndTerm>();
Collections.shuffle(allTerms, random());
int upto = 0;
while (upto < allTerms.size()) {
boolean useTermState = termStates.size() != 0 && random().nextInt(5) == 1;
FieldAndTerm fieldAndTerm;
TermsEnum termsEnum;
TermState termState = null;
if (!useTermState) {
// Seek by random field+term:
fieldAndTerm = allTerms.get(upto++);
if (VERBOSE) {
System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() );
}
} else {
// Seek by previous saved TermState
int idx = random().nextInt(termStates.size());
fieldAndTerm = termStateTerms.get(idx);
if (VERBOSE) {
System.out.println("\nTEST: seek using TermState to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString());
}
termState = termStates.get(idx);
}
Terms terms = fieldsSource.terms(fieldAndTerm.field);
assertNotNull(terms);
termsEnum = terms.iterator(null);
if (!useTermState) {
assertTrue(termsEnum.seekExact(fieldAndTerm.term, true));
} else {
termsEnum.seekExact(fieldAndTerm.term, termState);
}
boolean savedTermState = false;
if (options.contains(Option.TERM_STATE) && !useTermState && random().nextInt(5) == 1) {
// Save away this TermState:
termStates.add(termsEnum.termState());
termStateTerms.add(fieldAndTerm);
savedTermState = true;
}
verifyEnum(threadState,
fieldAndTerm.field,
fieldAndTerm.term,
termsEnum,
maxIndexOptions,
options,
alwaysTestMax);
// Sometimes save term state after pulling the enum:
if (options.contains(Option.TERM_STATE) && !useTermState && !savedTermState && random().nextInt(5) == 1) {
// Save away this TermState:
termStates.add(termsEnum.termState());
termStateTerms.add(fieldAndTerm);
useTermState = true;
}
// 10% of the time make sure you can pull another enum
// from the same term:
if (alwaysTestMax || random().nextInt(10) == 7) {
// Try same term again
if (VERBOSE) {
System.out.println("TEST: try enum again on same term");
}
verifyEnum(threadState,
fieldAndTerm.field,
fieldAndTerm.term,
termsEnum,
maxIndexOptions,
options,
alwaysTestMax);
}
}
}
private void testFields(Fields fields) throws Exception {
Iterator<String> iterator = fields.iterator();
while (iterator.hasNext()) {
String field = iterator.next();
try {
iterator.remove();
fail("Fields.iterator() allows for removal");
} catch (UnsupportedOperationException expected) {
// expected;
}
}
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("Fields.iterator() doesn't throw NoSuchElementException when past the end");
} catch (NoSuchElementException expected) {
// expected
}
}
/** Indexes all fields/terms at the specified
* IndexOptions, and fully tests at that IndexOptions. */
private void testFull(IndexOptions options, boolean withPayloads) throws Exception {
File path = _TestUtil.getTempDir("testPostingsFormat.testExact");
Directory dir = newFSDirectory(path);
// TODO test thread safety of buildIndex too
FieldsProducer fieldsProducer = buildIndex(dir, options, withPayloads, true);
testFields(fieldsProducer);
IndexOptions[] allOptions = IndexOptions.values();
int maxIndexOption = Arrays.asList(allOptions).indexOf(options);
for(int i=0;i<=maxIndexOption;i++) {
testTerms(fieldsProducer, EnumSet.allOf(Option.class), allOptions[i], true);
if (withPayloads) {
// If we indexed w/ payloads, also test enums w/o accessing payloads:
testTerms(fieldsProducer, EnumSet.complementOf(EnumSet.of(Option.PAYLOADS)), allOptions[i], true);
}
}
fieldsProducer.close();
dir.close();
_TestUtil.rmDir(path);
}
public void testDocsOnly() throws Exception {
testFull(IndexOptions.DOCS_ONLY, false);
}
public void testDocsAndFreqs() throws Exception {
testFull(IndexOptions.DOCS_AND_FREQS, false);
}
public void testDocsAndFreqsAndPositions() throws Exception {
testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, false);
}
public void testDocsAndFreqsAndPositionsAndPayloads() throws Exception {
testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, true);
}
public void testDocsAndFreqsAndPositionsAndOffsets() throws Exception {
testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);
}
public void testDocsAndFreqsAndPositionsAndOffsetsAndPayloads() throws Exception {
testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, true);
}
public void testRandom() throws Exception {
int iters = atLeast(10);
for(int iter=0;iter<iters;iter++) {
File path = _TestUtil.getTempDir("testPostingsFormat");
Directory dir = newFSDirectory(path);
boolean indexPayloads = random().nextBoolean();
// TODO test thread safety of buildIndex too
FieldsProducer fieldsProducer = buildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads, false);
testFields(fieldsProducer);
// NOTE: you can also test "weaker" index options than
// you indexed with:
testTerms(fieldsProducer, EnumSet.allOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);
fieldsProducer.close();
dir.close();
_TestUtil.rmDir(path);
}
}
}
| lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java | package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsConsumer;
import org.apache.lucene.codecs.TermStats;
import org.apache.lucene.codecs.TermsConsumer;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FlushInfo;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Abstract class to do basic tests for a postings format.
* NOTE: This test focuses on the postings
* (docs/freqs/positions/payloads/offsets) impl, not the
* terms dict. The [stretch] goal is for this test to be
* so thorough in testing a new PostingsFormat that if this
* test passes, then all Lucene/Solr tests should also pass. Ie,
* if there is some bug in a given PostingsFormat that this
* test fails to catch then this test needs to be improved! */
// TODO can we make it easy for testing to pair up a "random terms dict impl" with your postings base format...
// TODO test when you reuse after skipping a term or two, eg the block reuse case
// TODO hmm contract says .doc() can return NO_MORE_DOCS
// before nextDoc too...?
/* TODO
- threads
- assert doc=-1 before any nextDoc
- if a PF passes this test but fails other tests then this
test has a bug!!
- test tricky reuse cases, eg across fields
- verify you get null if you pass needFreq/needOffset but
they weren't indexed
*/
public abstract class BasePostingsFormatTestCase extends LuceneTestCase {
/**
* Returns the Codec to run tests against
*/
protected abstract Codec getCodec();
private enum Option {
// Sometimes use .advance():
SKIPPING,
// Sometimes reuse the Docs/AndPositionsEnum across terms:
REUSE_ENUMS,
// Sometimes pass non-null live docs:
LIVE_DOCS,
// Sometimes seek to term using previously saved TermState:
TERM_STATE,
// Sometimes don't fully consume docs from the enum
PARTIAL_DOC_CONSUME,
// Sometimes don't fully consume positions at each doc
PARTIAL_POS_CONSUME,
// Sometimes check payloads
PAYLOADS,
// Test w/ multiple threads
THREADS};
private static class FieldAndTerm {
String field;
BytesRef term;
public FieldAndTerm(String field, BytesRef term) {
this.field = field;
this.term = BytesRef.deepCopyOf(term);
}
}
private static class Position {
int position;
byte[] payload;
int startOffset;
int endOffset;
}
private static class Posting implements Comparable<Posting> {
int docID;
List<Position> positions;
public int compareTo(Posting other) {
return docID - other.docID;
}
}
// Holds all postings:
private static Map<String,Map<BytesRef,List<Posting>>> fields;
// Holds only live doc postings:
private static Map<String,Map<BytesRef,List<Posting>>> fieldsLive;
private static FieldInfos fieldInfos;
private static int maxDocID;
private static FixedBitSet globalLiveDocs;
private static List<FieldAndTerm> allTerms;
private static long totalPostings;
private static long totalPayloadBytes;
@BeforeClass
public static void createPostings() throws IOException {
fields = new TreeMap<String,Map<BytesRef,List<Posting>>>();
fieldsLive = new TreeMap<String,Map<BytesRef,List<Posting>>>();
final int numFields = _TestUtil.nextInt(random(), 1, 5);
if (VERBOSE) {
System.out.println("TEST: " + numFields + " fields");
}
FieldInfo[] fieldInfoArray = new FieldInfo[numFields];
int fieldUpto = 0;
int numMediumTerms = 0;
int numBigTerms = 0;
int numManyPositions = 0;
totalPostings = 0;
totalPayloadBytes = 0;
while (fieldUpto < numFields) {
String field = _TestUtil.randomSimpleString(random());
if (fields.containsKey(field)) {
continue;
}
boolean fieldHasPayloads = random().nextBoolean();
fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, fieldHasPayloads,
IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS,
null, DocValues.Type.FIXED_INTS_8, null);
fieldUpto++;
Map<BytesRef,List<Posting>> postings = new TreeMap<BytesRef,List<Posting>>();
fields.put(field, postings);
Set<String> seenTerms = new HashSet<String>();
// TODO
//final int numTerms = atLeast(10);
final int numTerms = 4;
for(int termUpto=0;termUpto<numTerms;termUpto++) {
String term = _TestUtil.randomSimpleString(random());
if (seenTerms.contains(term)) {
continue;
}
seenTerms.add(term);
int numDocs;
if (random().nextInt(10) == 3 && numBigTerms < 2) {
// 10% of the time make a highish freq term:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 50000, 70000);
numBigTerms++;
term = "big_" + term;
} else if (random().nextInt(10) == 3 && numMediumTerms < 5) {
// 10% of the time make a medium freq term:
// TODO not high enough to test level 1 skipping:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 3000, 6000);
numMediumTerms++;
term = "medium_" + term;
} else if (random().nextBoolean()) {
// Low freq term:
numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 1, 40);
term = "low_" + term;
} else {
// Very low freq term (don't multiply by RANDOM_MULTIPLIER):
numDocs = _TestUtil.nextInt(random(), 1, 3);
term = "verylow_" + term;
}
List<Posting> termPostings = new ArrayList<Posting>();
postings.put(new BytesRef(term), termPostings);
int docID = 0;
// TODO: more realistic to inversely tie this to numDocs:
int maxDocSpacing = _TestUtil.nextInt(random(), 1, 100);
// 10% of the time create big payloads:
int payloadSize;
if (!fieldHasPayloads) {
payloadSize = 0;
} else if (random().nextInt(10) == 7) {
payloadSize = random().nextInt(50);
} else {
payloadSize = random().nextInt(10);
}
boolean fixedPayloads = random().nextBoolean();
for(int docUpto=0;docUpto<numDocs;docUpto++) {
if (docUpto == 0 && random().nextBoolean()) {
// Sometimes index docID = 0
} else if (maxDocSpacing == 1) {
docID++;
} else {
// TODO: sometimes have a biggish gap here!
docID += _TestUtil.nextInt(random(), 1, maxDocSpacing);
}
Posting posting = new Posting();
posting.docID = docID;
maxDocID = Math.max(docID, maxDocID);
posting.positions = new ArrayList<Position>();
termPostings.add(posting);
int freq;
if (random().nextInt(30) == 17 && numManyPositions < 10) {
freq = _TestUtil.nextInt(random(), 1, 1000);
numManyPositions++;
} else {
freq = _TestUtil.nextInt(random(), 1, 20);
}
int pos = 0;
int offset = 0;
int posSpacing = _TestUtil.nextInt(random(), 1, 100);
totalPostings += freq;
for(int posUpto=0;posUpto<freq;posUpto++) {
if (posUpto == 0 && random().nextBoolean()) {
// Sometimes index pos = 0
} else if (posSpacing == 1) {
pos++;
} else {
pos += _TestUtil.nextInt(random(), 1, posSpacing);
}
Position position = new Position();
posting.positions.add(position);
position.position = pos;
if (payloadSize != 0) {
if (fixedPayloads) {
position.payload = new byte[payloadSize];
} else {
int thisPayloadSize = random().nextInt(payloadSize);
if (thisPayloadSize != 0) {
position.payload = new byte[thisPayloadSize];
}
}
}
if (position.payload != null) {
random().nextBytes(position.payload);
totalPayloadBytes += position.payload.length;
}
position.startOffset = offset + random().nextInt(5);
position.endOffset = position.startOffset + random().nextInt(10);
offset = position.endOffset;
}
}
}
}
fieldInfos = new FieldInfos(fieldInfoArray);
globalLiveDocs = new FixedBitSet(1+maxDocID);
double liveRatio = random().nextDouble();
for(int i=0;i<1+maxDocID;i++) {
if (random().nextDouble() <= liveRatio) {
globalLiveDocs.set(i);
}
}
// Pre-filter postings by globalLiveDocs:
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
Map<BytesRef,List<Posting>> postingsLive = new TreeMap<BytesRef,List<Posting>>();
fieldsLive.put(fieldEnt.getKey(), postingsLive);
for(Map.Entry<BytesRef,List<Posting>> termEnt : fieldEnt.getValue().entrySet()) {
List<Posting> termPostingsLive = new ArrayList<Posting>();
postingsLive.put(termEnt.getKey(), termPostingsLive);
for(Posting posting : termEnt.getValue()) {
if (globalLiveDocs.get(posting.docID)) {
termPostingsLive.add(posting);
}
}
}
}
allTerms = new ArrayList<FieldAndTerm>();
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
String field = fieldEnt.getKey();
for(Map.Entry<BytesRef,List<Posting>> termEnt : fieldEnt.getValue().entrySet()) {
allTerms.add(new FieldAndTerm(field, termEnt.getKey()));
}
}
if (VERBOSE) {
System.out.println("TEST: done init postings; maxDocID=" + maxDocID + "; " + allTerms.size() + " total terms, across " + fieldInfos.size() + " fields");
}
}
@AfterClass
public static void afterClass() throws Exception {
allTerms = null;
fieldInfos = null;
fields = null;
fieldsLive = null;
globalLiveDocs = null;
}
// TODO maybe instead of @BeforeClass just make a single test run: build postings & index & test it?
private FieldInfos currentFieldInfos;
// maxAllowed = the "highest" we can index, but we will still
// randomly index at lower IndexOption
private FieldsProducer buildIndex(Directory dir, IndexOptions maxAllowed, boolean allowPayloads) throws IOException {
Codec codec = getCodec();
SegmentInfo segmentInfo = new SegmentInfo(dir, Constants.LUCENE_MAIN_VERSION, "_0", 1+maxDocID, false, codec, null, null);
int maxIndexOption = Arrays.asList(IndexOptions.values()).indexOf(maxAllowed);
if (VERBOSE) {
System.out.println("\nTEST: now build index");
}
int maxIndexOptionNoOffsets = Arrays.asList(IndexOptions.values()).indexOf(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
// TODO use allowPayloads
FieldInfo[] newFieldInfoArray = new FieldInfo[fields.size()];
for(int fieldUpto=0;fieldUpto<fields.size();fieldUpto++) {
FieldInfo oldFieldInfo = fieldInfos.fieldInfo(fieldUpto);
String pf = _TestUtil.getPostingsFormat(codec, oldFieldInfo.name);
int fieldMaxIndexOption;
if (doesntSupportOffsets.contains(pf)) {
fieldMaxIndexOption = Math.min(maxIndexOptionNoOffsets, maxIndexOption);
} else {
fieldMaxIndexOption = maxIndexOption;
}
// Randomly picked the IndexOptions to index this
// field with:
IndexOptions indexOptions = IndexOptions.values()[random().nextInt(1+fieldMaxIndexOption)];
boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
newFieldInfoArray[fieldUpto] = new FieldInfo(oldFieldInfo.name,
true,
fieldUpto,
false,
false,
doPayloads,
indexOptions,
null,
DocValues.Type.FIXED_INTS_8,
null);
}
FieldInfos newFieldInfos = new FieldInfos(newFieldInfoArray);
// Estimate that flushed segment size will be 25% of
// what we use in RAM:
long bytes = totalPostings * 8 + totalPayloadBytes;
SegmentWriteState writeState = new SegmentWriteState(null, dir,
segmentInfo, newFieldInfos,
32, null, new IOContext(new FlushInfo(maxDocID, bytes)));
FieldsConsumer fieldsConsumer = codec.postingsFormat().fieldsConsumer(writeState);
for(Map.Entry<String,Map<BytesRef,List<Posting>>> fieldEnt : fields.entrySet()) {
String field = fieldEnt.getKey();
Map<BytesRef,List<Posting>> terms = fieldEnt.getValue();
FieldInfo fieldInfo = newFieldInfos.fieldInfo(field);
IndexOptions indexOptions = fieldInfo.getIndexOptions();
if (VERBOSE) {
System.out.println("field=" + field + " indexOtions=" + indexOptions);
}
boolean doFreq = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
boolean doPos = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
boolean doOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
TermsConsumer termsConsumer = fieldsConsumer.addField(fieldInfo);
long sumTotalTF = 0;
long sumDF = 0;
FixedBitSet seenDocs = new FixedBitSet(maxDocID+1);
for(Map.Entry<BytesRef,List<Posting>> termEnt : terms.entrySet()) {
BytesRef term = termEnt.getKey();
List<Posting> postings = termEnt.getValue();
if (VERBOSE) {
System.out.println(" term=" + field + ":" + term.utf8ToString() + " docFreq=" + postings.size());
}
PostingsConsumer postingsConsumer = termsConsumer.startTerm(term);
long totalTF = 0;
int docCount = 0;
for(Posting posting : postings) {
if (VERBOSE) {
System.out.println(" " + docCount + ": docID=" + posting.docID + " freq=" + posting.positions.size());
}
postingsConsumer.startDoc(posting.docID, doFreq ? posting.positions.size() : -1);
seenDocs.set(posting.docID);
if (doPos) {
totalTF += posting.positions.size();
for(Position pos : posting.positions) {
if (VERBOSE) {
if (doPayloads) {
System.out.println(" pos=" + pos.position + " payload=" + (pos.payload == null ? "null" : pos.payload.length + " bytes"));
} else {
System.out.println(" pos=" + pos.position);
}
}
postingsConsumer.addPosition(pos.position, (doPayloads && pos.payload != null) ? new BytesRef(pos.payload) : null, doOffsets ? pos.startOffset : -1, doOffsets ? pos.endOffset : -1);
}
} else if (doFreq) {
totalTF += posting.positions.size();
} else {
totalTF++;
}
postingsConsumer.finishDoc();
docCount++;
}
termsConsumer.finishTerm(term, new TermStats(postings.size(), doFreq ? totalTF : -1));
sumTotalTF += totalTF;
sumDF += postings.size();
}
termsConsumer.finish(doFreq ? sumTotalTF : -1, sumDF, seenDocs.cardinality());
}
fieldsConsumer.close();
if (VERBOSE) {
System.out.println("TEST: after indexing: files=");
for(String file : dir.listAll()) {
System.out.println(" " + file + ": " + dir.fileLength(file) + " bytes");
}
}
currentFieldInfos = newFieldInfos;
SegmentReadState readState = new SegmentReadState(dir, segmentInfo, newFieldInfos, IOContext.DEFAULT, 1);
return codec.postingsFormat().fieldsProducer(readState);
}
private static class ThreadState {
// Only used with REUSE option:
public DocsEnum reuseDocsEnum;
public DocsAndPositionsEnum reuseDocsAndPositionsEnum;
}
private void verifyEnum(ThreadState threadState,
String field,
BytesRef term,
TermsEnum termsEnum,
// Maximum options (docs/freqs/positions/offsets) to test:
IndexOptions maxIndexOptions,
EnumSet<Option> options) throws IOException {
if (VERBOSE) {
System.out.println(" verifyEnum: options=" + options + " maxIndexOptions=" + maxIndexOptions);
}
// 50% of the time time pass liveDocs:
Bits liveDocs;
Map<String,Map<BytesRef,List<Posting>>> fieldsToUse;
if (options.contains(Option.LIVE_DOCS) && random().nextBoolean()) {
liveDocs = globalLiveDocs;
fieldsToUse = fieldsLive;
if (VERBOSE) {
System.out.println(" use liveDocs");
}
} else {
liveDocs = null;
fieldsToUse = fields;
if (VERBOSE) {
System.out.println(" no liveDocs");
}
}
FieldInfo fieldInfo = currentFieldInfos.fieldInfo(field);
assertEquals(fields.get(field).get(term).size(), termsEnum.docFreq());
// NOTE: can be empty list if we are using liveDocs:
List<Posting> expected = fieldsToUse.get(field).get(term);
boolean allowFreqs = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
boolean doCheckFreqs = allowFreqs && random().nextInt(3) <= 2;
boolean allowPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
boolean doCheckPositions = allowPositions && random().nextInt(3) <= 2;
boolean allowOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0 &&
maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
boolean doCheckOffsets = allowOffsets && random().nextInt(3) <= 2;
boolean doCheckPayloads = options.contains(Option.PAYLOADS) && allowPositions && fieldInfo.hasPayloads() && random().nextInt(3) <= 2;
DocsEnum prevDocsEnum = null;
DocsEnum docsEnum;
DocsAndPositionsEnum docsAndPositionsEnum;
if (!doCheckPositions) {
if (allowPositions && random().nextInt(10) == 7) {
// 10% of the time, even though we will not check positions, pull a DocsAndPositions enum
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
}
int flags = 0;
if (random().nextBoolean()) {
flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
}
if (random().nextBoolean()) {
flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
}
if (VERBOSE) {
System.out.println(" get DocsAndPositionsEnum (but we won't check positions) flags=" + flags);
}
threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
docsEnum = threadState.reuseDocsAndPositionsEnum;
docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
} else {
if (VERBOSE) {
System.out.println(" get DocsEnum");
}
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsEnum;
}
threadState.reuseDocsEnum = termsEnum.docs(liveDocs, prevDocsEnum, doCheckFreqs ? DocsEnum.FLAG_FREQS : 0);
docsEnum = threadState.reuseDocsEnum;
docsAndPositionsEnum = null;
}
} else {
if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
}
int flags = 0;
if (doCheckOffsets || random().nextInt(3) == 1) {
flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
}
if (doCheckPayloads|| random().nextInt(3) == 1) {
flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
}
if (VERBOSE) {
System.out.println(" get DocsAndPositionsEnum flags=" + flags);
}
threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
docsEnum = threadState.reuseDocsAndPositionsEnum;
docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
}
assertNotNull("null DocsEnum", docsEnum);
int initialDocID = docsEnum.docID();
assertTrue("inital docID should be -1 or NO_MORE_DOCS: " + docsEnum, initialDocID == -1 || initialDocID == DocsEnum.NO_MORE_DOCS);
if (VERBOSE) {
if (prevDocsEnum == null) {
System.out.println(" got enum=" + docsEnum);
} else if (prevDocsEnum == docsEnum) {
System.out.println(" got reuse enum=" + docsEnum);
} else {
System.out.println(" got enum=" + docsEnum + " (reuse of " + prevDocsEnum + " failed)");
}
}
// 10% of the time don't consume all docs:
int stopAt;
if (options.contains(Option.PARTIAL_DOC_CONSUME) && expected.size() > 1 && random().nextInt(10) == 7) {
stopAt = random().nextInt(expected.size()-1);
if (VERBOSE) {
System.out.println(" will not consume all docs (" + stopAt + " vs " + expected.size() + ")");
}
} else {
stopAt = expected.size();
if (VERBOSE) {
System.out.println(" consume all docs");
}
}
double skipChance = random().nextDouble();
int numSkips = expected.size() < 3 ? 1 : _TestUtil.nextInt(random(), 1, Math.min(20, expected.size()/3));
int skipInc = expected.size()/numSkips;
int skipDocInc = (1+maxDocID)/numSkips;
// Sometimes do 100% skipping:
boolean doAllSkipping = options.contains(Option.SKIPPING) && random().nextInt(7) == 1;
double freqAskChance = random().nextDouble();
double payloadCheckChance = random().nextDouble();
double offsetCheckChance = random().nextDouble();
if (VERBOSE) {
if (options.contains(Option.SKIPPING)) {
System.out.println(" skipChance=" + skipChance + " numSkips=" + numSkips);
} else {
System.out.println(" no skipping");
}
if (doCheckFreqs) {
System.out.println(" freqAskChance=" + freqAskChance);
}
if (doCheckPayloads) {
System.out.println(" payloadCheckChance=" + payloadCheckChance);
}
if (doCheckOffsets) {
System.out.println(" offsetCheckChance=" + offsetCheckChance);
}
}
int nextPosting = 0;
while (nextPosting <= stopAt) {
if (nextPosting == stopAt) {
if (stopAt == expected.size()) {
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.nextDoc());
// Common bug is to forget to set this.doc=NO_MORE_DOCS in the enum!:
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.docID());
}
break;
}
Posting posting;
if (options.contains(Option.SKIPPING) && (doAllSkipping || random().nextDouble() <= skipChance)) {
int targetDocID = -1;
if (nextPosting < stopAt && random().nextBoolean()) {
// Pick target we know exists:
nextPosting = _TestUtil.nextInt(random(), nextPosting, nextPosting+skipInc);
} else {
// Pick random target (might not exist):
Posting target = new Posting();
target.docID = _TestUtil.nextInt(random(), expected.get(nextPosting).docID, expected.get(nextPosting).docID+skipDocInc);
targetDocID = target.docID;
int loc = Collections.binarySearch(expected.subList(nextPosting, expected.size()), target);
if (loc < 0) {
loc = -loc-1;
}
nextPosting = nextPosting + loc;
}
if (nextPosting >= stopAt) {
int target = random().nextBoolean() ? (maxDocID+1) : DocsEnum.NO_MORE_DOCS;
if (VERBOSE) {
System.out.println(" now advance to end (target=" + target + ")");
}
assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.advance(target));
break;
} else {
posting = expected.get(nextPosting++);
if (VERBOSE) {
if (targetDocID != -1) {
System.out.println(" now advance to random target=" + targetDocID + " (" + nextPosting + " of " + stopAt + ")");
} else {
System.out.println(" now advance to known-exists target=" + posting.docID + " (" + nextPosting + " of " + stopAt + ")");
}
}
int docID = docsEnum.advance(targetDocID != -1 ? targetDocID : posting.docID);
assertEquals("docID is wrong", posting.docID, docID);
}
} else {
posting = expected.get(nextPosting++);
if (VERBOSE) {
System.out.println(" now nextDoc to " + posting.docID + " (" + nextPosting + " of " + stopAt + ")");
}
int docID = docsEnum.nextDoc();
assertEquals("docID is wrong", posting.docID, docID);
}
if (doCheckFreqs && random().nextDouble() <= freqAskChance) {
if (VERBOSE) {
System.out.println(" now freq()=" + posting.positions.size());
}
int freq = docsEnum.freq();
assertEquals("freq is wrong", posting.positions.size(), freq);
}
if (doCheckPositions) {
int freq = docsEnum.freq();
int numPosToConsume;
if (options.contains(Option.PARTIAL_POS_CONSUME) && random().nextInt(5) == 1) {
numPosToConsume = random().nextInt(freq);
} else {
numPosToConsume = freq;
}
for(int i=0;i<numPosToConsume;i++) {
Position position = posting.positions.get(i);
if (VERBOSE) {
System.out.println(" now nextPosition to " + position.position);
}
assertEquals("position is wrong", position.position, docsAndPositionsEnum.nextPosition());
// TODO sometimes don't pull the payload even
// though we pulled the position
if (doCheckPayloads) {
if (random().nextDouble() <= payloadCheckChance) {
if (VERBOSE) {
System.out.println(" now check payload length=" + (position.payload == null ? 0 : position.payload.length));
}
if (position.payload == null || position.payload.length == 0) {
assertNull("should not have payload", docsAndPositionsEnum.getPayload());
} else {
BytesRef payload = docsAndPositionsEnum.getPayload();
assertNotNull("should have payload but doesn't", payload);
assertEquals("payload length is wrong", position.payload.length, payload.length);
for(int byteUpto=0;byteUpto<position.payload.length;byteUpto++) {
assertEquals("payload bytes are wrong",
position.payload[byteUpto],
payload.bytes[payload.offset+byteUpto]);
}
// make a deep copy
payload = BytesRef.deepCopyOf(payload);
assertEquals("2nd call to getPayload returns something different!", payload, docsAndPositionsEnum.getPayload());
}
} else {
if (VERBOSE) {
System.out.println(" skip check payload length=" + (position.payload == null ? 0 : position.payload.length));
}
}
}
if (doCheckOffsets) {
if (random().nextDouble() <= offsetCheckChance) {
if (VERBOSE) {
System.out.println(" now check offsets: startOff=" + position.startOffset + " endOffset=" + position.endOffset);
}
assertEquals("startOffset is wrong", position.startOffset, docsAndPositionsEnum.startOffset());
assertEquals("endOffset is wrong", position.endOffset, docsAndPositionsEnum.endOffset());
} else {
if (VERBOSE) {
System.out.println(" skip check offsets");
}
}
} else {
if (VERBOSE) {
System.out.println(" now check offsets are -1");
}
assertEquals("startOffset isn't -1", -1, docsAndPositionsEnum.startOffset());
assertEquals("endOffset isn't -1", -1, docsAndPositionsEnum.endOffset());
}
}
}
}
}
private void testTerms(final Fields fieldsSource, final EnumSet<Option> options, final IndexOptions maxIndexOptions) throws Exception {
if (options.contains(Option.THREADS)) {
int numThreads = _TestUtil.nextInt(random(), 2, 5);
Thread[] threads = new Thread[numThreads];
for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
threads[threadUpto] = new Thread() {
@Override
public void run() {
try {
testTermsOneThread(fieldsSource, options, maxIndexOptions);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
};
threads[threadUpto].start();
}
for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
threads[threadUpto].join();
}
} else {
testTermsOneThread(fieldsSource, options, maxIndexOptions);
}
}
private void testTermsOneThread(Fields fieldsSource, EnumSet<Option> options, IndexOptions maxIndexOptions) throws IOException {
ThreadState threadState = new ThreadState();
// Test random terms/fields:
List<TermState> termStates = new ArrayList<TermState>();
List<FieldAndTerm> termStateTerms = new ArrayList<FieldAndTerm>();
Collections.shuffle(allTerms, random());
int upto = 0;
while (upto < allTerms.size()) {
boolean useTermState = termStates.size() != 0 && random().nextInt(5) == 1;
FieldAndTerm fieldAndTerm;
TermsEnum termsEnum;
TermState termState = null;
if (!useTermState) {
// Seek by random field+term:
fieldAndTerm = allTerms.get(upto++);
if (VERBOSE) {
System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() );
}
} else {
// Seek by previous saved TermState
int idx = random().nextInt(termStates.size());
fieldAndTerm = termStateTerms.get(idx);
if (VERBOSE) {
System.out.println("\nTEST: seek using TermState to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString());
}
termState = termStates.get(idx);
}
Terms terms = fieldsSource.terms(fieldAndTerm.field);
assertNotNull(terms);
termsEnum = terms.iterator(null);
if (!useTermState) {
assertTrue(termsEnum.seekExact(fieldAndTerm.term, true));
} else {
termsEnum.seekExact(fieldAndTerm.term, termState);
}
boolean savedTermState = false;
if (options.contains(Option.TERM_STATE) && !useTermState && random().nextInt(5) == 1) {
// Save away this TermState:
termStates.add(termsEnum.termState());
termStateTerms.add(fieldAndTerm);
savedTermState = true;
}
verifyEnum(threadState,
fieldAndTerm.field,
fieldAndTerm.term,
termsEnum,
maxIndexOptions,
options);
// Sometimes save term state after pulling the enum:
if (options.contains(Option.TERM_STATE) && !useTermState && !savedTermState && random().nextInt(5) == 1) {
// Save away this TermState:
termStates.add(termsEnum.termState());
termStateTerms.add(fieldAndTerm);
useTermState = true;
}
// 10% of the time make sure you can pull another enum
// from the same term:
if (random().nextInt(10) == 7) {
// Try same term again
if (VERBOSE) {
System.out.println("TEST: try enum again on same term");
}
verifyEnum(threadState,
fieldAndTerm.field,
fieldAndTerm.term,
termsEnum,
maxIndexOptions,
options);
}
}
}
private void testFields(Fields fields) throws Exception {
Iterator<String> iterator = fields.iterator();
while (iterator.hasNext()) {
String field = iterator.next();
try {
iterator.remove();
fail("Fields.iterator() allows for removal");
} catch (UnsupportedOperationException expected) {
// expected;
}
}
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("Fields.iterator() doesn't throw NoSuchElementException when past the end");
} catch (NoSuchElementException expected) {
// expected
}
}
public void test() throws Exception {
Directory dir = newFSDirectory(_TestUtil.getTempDir("testPostingsFormat"));
boolean indexPayloads = random().nextBoolean();
// TODO test thread safety of buildIndex too
FieldsProducer fieldsProducer = buildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads);
testFields(fieldsProducer);
//testTerms(fieldsProducer, EnumSet.noneOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
//testTerms(fieldsProducer, EnumSet.of(Option.LIVE_DOCS), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
//testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.LIVE_DOCS, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
//testTerms(fieldsProducer, EnumSet.of(Option.SKIPPING), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
//testTerms(fieldsProducer, EnumSet.of(Option.THREADS, Option.TERM_STATE, Option.SKIPPING, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
//testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.SKIPPING, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
//testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.PAYLOADS, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME, Option.SKIPPING), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
// NOTE: you can also test "weaker" index options than
// you indexed with:
testTerms(fieldsProducer, EnumSet.allOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
//testTerms(fieldsProducer, EnumSet.complementOf(EnumSet.of(Option.THREADS)), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
fieldsProducer.close();
dir.close();
}
}
// TODO test that start/endOffset return -1 if field has
// no offsets
| add more deterministic tests; increase iters for testRandom
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1391866 13f79535-47bb-0310-9956-ffa450edef68
| lucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java | add more deterministic tests; increase iters for testRandom | <ide><path>ucene/test-framework/src/java/org/apache/lucene/index/BasePostingsFormatTestCase.java
<ide> * limitations under the License.
<ide> */
<ide>
<add>import java.io.File;
<ide> import java.io.IOException;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> continue;
<ide> }
<ide>
<del> boolean fieldHasPayloads = random().nextBoolean();
<del>
<del> fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, fieldHasPayloads,
<add> fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, true,
<ide> IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS,
<ide> null, DocValues.Type.FIXED_INTS_8, null);
<ide> fieldUpto++;
<ide> fields.put(field, postings);
<ide> Set<String> seenTerms = new HashSet<String>();
<ide>
<del> // TODO
<del> //final int numTerms = atLeast(10);
<del> final int numTerms = 4;
<add> final int numTerms = atLeast(10);
<ide> for(int termUpto=0;termUpto<numTerms;termUpto++) {
<ide> String term = _TestUtil.randomSimpleString(random());
<ide> if (seenTerms.contains(term)) {
<ide> seenTerms.add(term);
<ide>
<ide> int numDocs;
<del> if (random().nextInt(10) == 3 && numBigTerms < 2) {
<del> // 10% of the time make a highish freq term:
<add> if (numBigTerms == 0 || (random().nextInt(10) == 3 && numBigTerms < 2)) {
<add> // Make at least 1 big term, then maybe (~10%
<add> // chance) make another:
<ide> numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 50000, 70000);
<ide> numBigTerms++;
<ide> term = "big_" + term;
<del> } else if (random().nextInt(10) == 3 && numMediumTerms < 5) {
<del> // 10% of the time make a medium freq term:
<del> // TODO not high enough to test level 1 skipping:
<add> } else if (numMediumTerms == 0 || (random().nextInt(10) == 3 && numMediumTerms < 5)) {
<add> // Make at least 1 medium term, then maybe (~10%
<add> // chance) make up to 4 more:
<ide> numDocs = RANDOM_MULTIPLIER * _TestUtil.nextInt(random(), 3000, 6000);
<ide> numMediumTerms++;
<ide> term = "medium_" + term;
<ide> // TODO: more realistic to inversely tie this to numDocs:
<ide> int maxDocSpacing = _TestUtil.nextInt(random(), 1, 100);
<ide>
<del> // 10% of the time create big payloads:
<ide> int payloadSize;
<del> if (!fieldHasPayloads) {
<del> payloadSize = 0;
<del> } else if (random().nextInt(10) == 7) {
<add> if (random().nextInt(10) == 7) {
<add> // 10% of the time create big payloads:
<ide> payloadSize = random().nextInt(50);
<ide> } else {
<ide> payloadSize = random().nextInt(10);
<ide>
<ide> // maxAllowed = the "highest" we can index, but we will still
<ide> // randomly index at lower IndexOption
<del> private FieldsProducer buildIndex(Directory dir, IndexOptions maxAllowed, boolean allowPayloads) throws IOException {
<add> private FieldsProducer buildIndex(Directory dir, IndexOptions maxAllowed, boolean allowPayloads, boolean alwaysTestMax) throws IOException {
<ide> Codec codec = getCodec();
<ide> SegmentInfo segmentInfo = new SegmentInfo(dir, Constants.LUCENE_MAIN_VERSION, "_0", 1+maxDocID, false, codec, null, null);
<ide>
<ide>
<ide> // Randomly picked the IndexOptions to index this
<ide> // field with:
<del> IndexOptions indexOptions = IndexOptions.values()[random().nextInt(1+fieldMaxIndexOption)];
<add> IndexOptions indexOptions = IndexOptions.values()[alwaysTestMax ? fieldMaxIndexOption : random().nextInt(1+fieldMaxIndexOption)];
<ide> boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
<ide>
<ide> newFieldInfoArray[fieldUpto] = new FieldInfo(oldFieldInfo.name,
<ide> // Maximum options (docs/freqs/positions/offsets) to test:
<ide> IndexOptions maxIndexOptions,
<ide>
<del> EnumSet<Option> options) throws IOException {
<add> EnumSet<Option> options,
<add> boolean alwaysTestMax) throws IOException {
<ide>
<ide> if (VERBOSE) {
<ide> System.out.println(" verifyEnum: options=" + options + " maxIndexOptions=" + maxIndexOptions);
<ide>
<ide> boolean allowFreqs = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0 &&
<ide> maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
<del> boolean doCheckFreqs = allowFreqs && random().nextInt(3) <= 2;
<add> boolean doCheckFreqs = allowFreqs && (alwaysTestMax || random().nextInt(3) <= 2);
<ide>
<ide> boolean allowPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 &&
<ide> maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
<del> boolean doCheckPositions = allowPositions && random().nextInt(3) <= 2;
<add> boolean doCheckPositions = allowPositions && (alwaysTestMax || random().nextInt(3) <= 2);
<ide>
<ide> boolean allowOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0 &&
<ide> maxIndexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
<del> boolean doCheckOffsets = allowOffsets && random().nextInt(3) <= 2;
<del>
<del> boolean doCheckPayloads = options.contains(Option.PAYLOADS) && allowPositions && fieldInfo.hasPayloads() && random().nextInt(3) <= 2;
<add> boolean doCheckOffsets = allowOffsets && (alwaysTestMax || random().nextInt(3) <= 2);
<add>
<add> boolean doCheckPayloads = options.contains(Option.PAYLOADS) && allowPositions && fieldInfo.hasPayloads() && (alwaysTestMax || random().nextInt(3) <= 2);
<ide>
<ide> DocsEnum prevDocsEnum = null;
<ide>
<ide> }
<ide>
<ide> int flags = 0;
<del> if (random().nextBoolean()) {
<add> if (alwaysTestMax || random().nextBoolean()) {
<ide> flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
<ide> }
<del> if (random().nextBoolean()) {
<add> if (alwaysTestMax || random().nextBoolean()) {
<ide> flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
<ide> }
<ide>
<ide> }
<ide>
<ide> int flags = 0;
<del> if (doCheckOffsets || random().nextInt(3) == 1) {
<add> if (alwaysTestMax || doCheckOffsets || random().nextInt(3) == 1) {
<ide> flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
<ide> }
<del> if (doCheckPayloads|| random().nextInt(3) == 1) {
<add> if (alwaysTestMax || doCheckPayloads|| random().nextInt(3) == 1) {
<ide> flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
<ide> }
<ide>
<ide>
<ide> // 10% of the time don't consume all docs:
<ide> int stopAt;
<del> if (options.contains(Option.PARTIAL_DOC_CONSUME) && expected.size() > 1 && random().nextInt(10) == 7) {
<add> if (!alwaysTestMax && options.contains(Option.PARTIAL_DOC_CONSUME) && expected.size() > 1 && random().nextInt(10) == 7) {
<ide> stopAt = random().nextInt(expected.size()-1);
<ide> if (VERBOSE) {
<ide> System.out.println(" will not consume all docs (" + stopAt + " vs " + expected.size() + ")");
<ide> }
<ide> }
<ide>
<del> double skipChance = random().nextDouble();
<add> double skipChance = alwaysTestMax ? 0.5 : random().nextDouble();
<ide> int numSkips = expected.size() < 3 ? 1 : _TestUtil.nextInt(random(), 1, Math.min(20, expected.size()/3));
<ide> int skipInc = expected.size()/numSkips;
<ide> int skipDocInc = (1+maxDocID)/numSkips;
<ide> // Sometimes do 100% skipping:
<ide> boolean doAllSkipping = options.contains(Option.SKIPPING) && random().nextInt(7) == 1;
<ide>
<del> double freqAskChance = random().nextDouble();
<del> double payloadCheckChance = random().nextDouble();
<del> double offsetCheckChance = random().nextDouble();
<add> double freqAskChance = alwaysTestMax ? 1.0 : random().nextDouble();
<add> double payloadCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();
<add> double offsetCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();
<ide>
<ide> if (VERBOSE) {
<ide> if (options.contains(Option.SKIPPING)) {
<ide> if (doCheckPositions) {
<ide> int freq = docsEnum.freq();
<ide> int numPosToConsume;
<del> if (options.contains(Option.PARTIAL_POS_CONSUME) && random().nextInt(5) == 1) {
<add> if (!alwaysTestMax && options.contains(Option.PARTIAL_POS_CONSUME) && random().nextInt(5) == 1) {
<ide> numPosToConsume = random().nextInt(freq);
<ide> } else {
<ide> numPosToConsume = freq;
<ide> System.out.println(" skip check offsets");
<ide> }
<ide> }
<del> } else {
<add> } else if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
<ide> if (VERBOSE) {
<ide> System.out.println(" now check offsets are -1");
<ide> }
<ide> }
<ide> }
<ide>
<del> private void testTerms(final Fields fieldsSource, final EnumSet<Option> options, final IndexOptions maxIndexOptions) throws Exception {
<add> private void testTerms(final Fields fieldsSource, final EnumSet<Option> options,
<add> final IndexOptions maxIndexOptions,
<add> final boolean alwaysTestMax) throws Exception {
<ide>
<ide> if (options.contains(Option.THREADS)) {
<ide> int numThreads = _TestUtil.nextInt(random(), 2, 5);
<ide> @Override
<ide> public void run() {
<ide> try {
<del> testTermsOneThread(fieldsSource, options, maxIndexOptions);
<add> testTermsOneThread(fieldsSource, options, maxIndexOptions, alwaysTestMax);
<ide> } catch (Throwable t) {
<ide> throw new RuntimeException(t);
<ide> }
<ide> threads[threadUpto].join();
<ide> }
<ide> } else {
<del> testTermsOneThread(fieldsSource, options, maxIndexOptions);
<del> }
<del> }
<del>
<del> private void testTermsOneThread(Fields fieldsSource, EnumSet<Option> options, IndexOptions maxIndexOptions) throws IOException {
<add> testTermsOneThread(fieldsSource, options, maxIndexOptions, alwaysTestMax);
<add> }
<add> }
<add>
<add> private void testTermsOneThread(Fields fieldsSource, EnumSet<Option> options, IndexOptions maxIndexOptions, boolean alwaysTestMax) throws IOException {
<ide>
<ide> ThreadState threadState = new ThreadState();
<ide>
<ide> fieldAndTerm.term,
<ide> termsEnum,
<ide> maxIndexOptions,
<del> options);
<add> options,
<add> alwaysTestMax);
<ide>
<ide> // Sometimes save term state after pulling the enum:
<ide> if (options.contains(Option.TERM_STATE) && !useTermState && !savedTermState && random().nextInt(5) == 1) {
<ide>
<ide> // 10% of the time make sure you can pull another enum
<ide> // from the same term:
<del> if (random().nextInt(10) == 7) {
<add> if (alwaysTestMax || random().nextInt(10) == 7) {
<ide> // Try same term again
<ide> if (VERBOSE) {
<ide> System.out.println("TEST: try enum again on same term");
<ide> fieldAndTerm.term,
<ide> termsEnum,
<ide> maxIndexOptions,
<del> options);
<add> options,
<add> alwaysTestMax);
<ide> }
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<del> public void test() throws Exception {
<del> Directory dir = newFSDirectory(_TestUtil.getTempDir("testPostingsFormat"));
<del>
<del> boolean indexPayloads = random().nextBoolean();
<add> /** Indexes all fields/terms at the specified
<add> * IndexOptions, and fully tests at that IndexOptions. */
<add> private void testFull(IndexOptions options, boolean withPayloads) throws Exception {
<add> File path = _TestUtil.getTempDir("testPostingsFormat.testExact");
<add> Directory dir = newFSDirectory(path);
<add>
<ide> // TODO test thread safety of buildIndex too
<del>
<del> FieldsProducer fieldsProducer = buildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads);
<add> FieldsProducer fieldsProducer = buildIndex(dir, options, withPayloads, true);
<ide>
<ide> testFields(fieldsProducer);
<del> //testTerms(fieldsProducer, EnumSet.noneOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
<del> //testTerms(fieldsProducer, EnumSet.of(Option.LIVE_DOCS), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
<del> //testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.LIVE_DOCS, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
<del>
<del> //testTerms(fieldsProducer, EnumSet.of(Option.SKIPPING), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
<del> //testTerms(fieldsProducer, EnumSet.of(Option.THREADS, Option.TERM_STATE, Option.SKIPPING, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
<del> //testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.SKIPPING, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
<del> //testTerms(fieldsProducer, EnumSet.of(Option.TERM_STATE, Option.PAYLOADS, Option.PARTIAL_DOC_CONSUME, Option.PARTIAL_POS_CONSUME, Option.SKIPPING), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
<del>
<del> // NOTE: you can also test "weaker" index options than
<del> // you indexed with:
<del> testTerms(fieldsProducer, EnumSet.allOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
<del> //testTerms(fieldsProducer, EnumSet.complementOf(EnumSet.of(Option.THREADS)), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
<add>
<add> IndexOptions[] allOptions = IndexOptions.values();
<add> int maxIndexOption = Arrays.asList(allOptions).indexOf(options);
<add>
<add> for(int i=0;i<=maxIndexOption;i++) {
<add> testTerms(fieldsProducer, EnumSet.allOf(Option.class), allOptions[i], true);
<add> if (withPayloads) {
<add> // If we indexed w/ payloads, also test enums w/o accessing payloads:
<add> testTerms(fieldsProducer, EnumSet.complementOf(EnumSet.of(Option.PAYLOADS)), allOptions[i], true);
<add> }
<add> }
<ide>
<ide> fieldsProducer.close();
<ide> dir.close();
<add> _TestUtil.rmDir(path);
<add> }
<add>
<add> public void testDocsOnly() throws Exception {
<add> testFull(IndexOptions.DOCS_ONLY, false);
<add> }
<add>
<add> public void testDocsAndFreqs() throws Exception {
<add> testFull(IndexOptions.DOCS_AND_FREQS, false);
<add> }
<add>
<add> public void testDocsAndFreqsAndPositions() throws Exception {
<add> testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, false);
<add> }
<add>
<add> public void testDocsAndFreqsAndPositionsAndPayloads() throws Exception {
<add> testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, true);
<add> }
<add>
<add> public void testDocsAndFreqsAndPositionsAndOffsets() throws Exception {
<add> testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);
<add> }
<add>
<add> public void testDocsAndFreqsAndPositionsAndOffsetsAndPayloads() throws Exception {
<add> testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, true);
<add> }
<add>
<add> public void testRandom() throws Exception {
<add>
<add> int iters = atLeast(10);
<add>
<add> for(int iter=0;iter<iters;iter++) {
<add> File path = _TestUtil.getTempDir("testPostingsFormat");
<add> Directory dir = newFSDirectory(path);
<add>
<add> boolean indexPayloads = random().nextBoolean();
<add> // TODO test thread safety of buildIndex too
<add> FieldsProducer fieldsProducer = buildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads, false);
<add>
<add> testFields(fieldsProducer);
<add>
<add> // NOTE: you can also test "weaker" index options than
<add> // you indexed with:
<add> testTerms(fieldsProducer, EnumSet.allOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);
<add>
<add> fieldsProducer.close();
<add> dir.close();
<add> _TestUtil.rmDir(path);
<add> }
<ide> }
<ide> }
<del>
<del>// TODO test that start/endOffset return -1 if field has
<del>// no offsets |
|
Java | apache-2.0 | fad95c69ffeb8b443eb6c530fdf9a90b3db18238 | 0 | cloudnautique/cattle,rancher/cattle,Cerfoglg/cattle,rancherio/cattle,cjellick/cattle,Cerfoglg/cattle,rancher/cattle,rancherio/cattle,cjellick/cattle,cloudnautique/cattle,cloudnautique/cattle,cjellick/cattle,wlan0/cattle,cjellick/cattle,rancherio/cattle,rancher/cattle,vincent99/cattle,wlan0/cattle,wlan0/cattle,cloudnautique/cattle,vincent99/cattle,vincent99/cattle,Cerfoglg/cattle | package io.cattle.platform.ha.monitor.impl;
import static io.cattle.platform.core.constants.ContainerEventConstants.*;
import static io.cattle.platform.core.constants.HostConstants.*;
import static io.cattle.platform.core.constants.InstanceConstants.*;
import io.cattle.platform.agent.AgentLocator;
import io.cattle.platform.agent.RemoteAgent;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.AgentDao;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.ContainerEvent;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.eventing.model.Event;
import io.cattle.platform.framework.event.Ping;
import io.cattle.platform.framework.event.data.PingData;
import io.cattle.platform.ha.monitor.PingInstancesMonitor;
import io.cattle.platform.ha.monitor.dao.PingInstancesMonitorDao;
import io.cattle.platform.ha.monitor.event.InstanceForceStop;
import io.cattle.platform.ha.monitor.model.KnownInstance;
import io.cattle.platform.lock.LockDelegator;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.util.type.CollectionUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.netflix.config.DynamicLongProperty;
public class PingInstancesMonitorImpl implements PingInstancesMonitor {
private static final DynamicLongProperty CACHE_TIME = ArchaiusUtil.getLong("ha.instance.state.cache.millis");
private static final DynamicLongProperty HOST_ID_CACHE_TIME = ArchaiusUtil.getLong("ha.host.id.cache.millis");
private static final Logger log = LoggerFactory.getLogger(PingInstancesMonitorImpl.class);
private static final String UKNOWN_OUT_OF_SYNC_WARNING = "Instance out of sync and can't determine action to take. Uuid [{}]. Docker id [{}]. "
+ "State in rancher [{}]. State on host [{}]";
@Inject
AgentDao agentDao;
@Inject
ObjectMetaDataManager objectMetaDataManager;
@Inject
AgentLocator agentLocator;
@Inject
LockDelegator lockDelegator;
@Inject
PingInstancesMonitorDao monitorDao;
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager processManager;
Cache<String, String> scheduled = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.MINUTES)
.build();
LoadingCache<Long, Map<String, KnownInstance>> instanceCache = CacheBuilder.newBuilder().expireAfterWrite(CACHE_TIME.get(), TimeUnit.MILLISECONDS)
.build(new CacheLoader<Long, Map<String, KnownInstance>>() {
@Override
public Map<String, KnownInstance> load(Long key) throws Exception {
return PingInstancesMonitorImpl.this.load(key);
}
});
LoadingCache<ImmutablePair<Long, String>, AgentAndHost> hostCache = CacheBuilder.newBuilder()
.expireAfterWrite(HOST_ID_CACHE_TIME.get(), TimeUnit.MILLISECONDS).build(new CacheLoader<ImmutablePair<Long, String>, AgentAndHost>() {
@Override
public AgentAndHost load(ImmutablePair<Long, String> key) throws Exception {
return PingInstancesMonitorImpl.this.loadAgentAndHostData(key);
}
});
@Override
public void pingReply(Ping ping) {
ReportedInstances reportedInstances = getInstances(ping);
if (reportedInstances == null || StringUtils.isEmpty(reportedInstances.hostUuid))
return;
long agentId = Long.parseLong(ping.getResourceId());
Map<String, KnownInstance> knownInstances = instanceCache.getUnchecked(agentId);
AgentAndHost agentAndHost = null;
try {
agentAndHost = hostCache.getUnchecked(new ImmutablePair<Long, String>(agentId, reportedInstances.hostUuid));
} catch (UncheckedExecutionException e) {
// CantFindAgentAndHostException can be ignored because the host may not exist yet. Rethrow all other exceptions.
if (!(e.getCause() instanceof CantFindAgentAndHostException)) {
throw e;
}
}
if (agentAndHost == null) {
log.info("Couldn't find host with uuid [{}] for agent [{}]", reportedInstances.hostUuid, agentId);
return;
}
try {
syncContainers(knownInstances, reportedInstances, agentAndHost.agentAccountId, agentId, agentAndHost.hostId, true);
} catch (ContainersOutOfSync e) {
knownInstances = load(agentId);
instanceCache.put(agentId, knownInstances);
syncContainers(knownInstances, reportedInstances, agentAndHost.agentAccountId, agentId, agentAndHost.hostId, false);
}
}
@Override
public void computeInstanceActivateReply(Event event) {
Long agentId = monitorDao.getAgentIdForInstanceHostMap(event.getResourceId());
if (agentId != null) {
instanceCache.invalidate(agentId);
}
}
/*
* If checkOnly is true, will raise a ContainersOutOfSync exception, indicating this should be reran with checkOnly set to false.
*/
void syncContainers(Map<String, KnownInstance> knownInstances, ReportedInstances reportedInstances, long agentAccountId, long agentId, long hostId,
boolean checkOnly) {
Map<String, ReportedInstance> needsSynced = new HashMap<String, ReportedInstance>();
Map<String, String> syncActions = new HashMap<String, String>();
determineSyncActions(knownInstances, reportedInstances, needsSynced, syncActions, checkOnly);
for (Map.Entry<String, ReportedInstance> syncEntry : needsSynced.entrySet()) {
ReportedInstance ri = syncEntry.getValue();
String syncAction = syncActions.get(syncEntry.getKey());
if (EVENT_INSTANCE_FORCE_STOP.equals(syncAction)) {
forceStop(ri.getExternalId(), agentId);
} else {
scheduleContainerEvent(agentAccountId, hostId, ri, syncAction);
}
}
}
void determineSyncActions(Map<String, KnownInstance> knownInstances, ReportedInstances reportedInstances, Map<String, ReportedInstance> needsSynced,
Map<String, String> syncActions, boolean checkOnly) {
Map<String, KnownInstance> inRancher = new HashMap<String, KnownInstance>(knownInstances);
Map<String, ReportedInstance> onHost = new HashMap<String, ReportedInstance>(reportedInstances.byExternalId);
for (Map.Entry<String, ReportedInstance> reported : reportedInstances.byUuid.entrySet()) {
KnownInstance ki = knownInstances.get(reported.getKey());
if (ki != null) {
removeAndDetermineSyncAction(needsSynced, syncActions, checkOnly, inRancher, onHost, reported.getValue(), ki,
reported.getValue().getExternalId(), reported.getKey());
}
}
if (!onHost.isEmpty() || !inRancher.isEmpty()) {
Map<String, KnownInstance> knownByExternalId = new HashMap<String, KnownInstance>();
for (KnownInstance ki : knownInstances.values()) {
if (StringUtils.isNotEmpty(ki.getExternalId()))
knownByExternalId.put(ki.getExternalId(), ki);
}
for (Map.Entry<String, ReportedInstance> reported : reportedInstances.byExternalId.entrySet()) {
KnownInstance ki = knownByExternalId.get(reported.getKey());
if (ki != null) {
removeAndDetermineSyncAction(needsSynced, syncActions, checkOnly, inRancher, onHost, reported.getValue(), ki,
reported.getKey(), ki.getUuid());
}
}
}
// Anything left in onHost is on the host, but not in rancher.
for (Map.Entry<String, ReportedInstance> create : onHost.entrySet()) {
ReportedInstance ri = create.getValue();
addSyncAction(needsSynced, syncActions, ri, EVENT_START, checkOnly);
}
// Anything left in inRancher is in rancher, but not on the host.
for (KnownInstance ki : inRancher.values()) {
List<String> forRemove = Arrays.asList(CommonStatesConstants.REMOVING, InstanceConstants.STATE_ERROR,
InstanceConstants.STATE_ERRORING);
if (objectMetaDataManager.isTransitioningState(Instance.class, ki.getState()) || ki.getRemoved() != null
|| forRemove.contains(ki.getState())
|| (STATE_STOPPED.equals(ki.getState()) && StringUtils.isEmpty(ki.getExternalId())))
continue;
ReportedInstance ri = new ReportedInstance();
ri.setExternalId(ki.getExternalId());
ri.setUuid(ki.getUuid());
Object imageUuid = CollectionUtils.getNestedValue(ki.getData(), DataUtils.FIELDS, FIELD_IMAGE_UUID);
String image = imageUuid != null ? imageUuid.toString() : null;
ri.setImage(image);
addSyncAction(needsSynced, syncActions, ri, EVENT_DESTROY, checkOnly);
}
}
void removeAndDetermineSyncAction(Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions, boolean checkOnly,
Map<String, KnownInstance> inRancher, Map<String, ReportedInstance> onHost, ReportedInstance reportedInstance, KnownInstance instance,
String onHostKey, String inRancherKey) {
onHost.remove(onHostKey);
inRancher.remove(inRancherKey);
reportedInstance.setInstance(instance);
determineSyncAction(instance, reportedInstance, needsSynced, syncActions, checkOnly);
}
void determineSyncAction(KnownInstance ki, ReportedInstance ri, Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions,
boolean checkOnly) {
if (objectMetaDataManager.isTransitioningState(Instance.class, ki.getState()) || StringUtils.equals(ki.getState(), ri.getState()))
return;
if (STATE_RUNNING.equals(ri.getState())) {
// Container is running on host but not in Rancher. Take action
if (ki.getRemoved() != null) {
// If rancher thinks it's removed, send an explicit stop down to host.
addSyncAction(needsSynced, syncActions, ri, EVENT_INSTANCE_FORCE_STOP, checkOnly);
} else if (STATE_STOPPED.equals(ki.getState())) {
// For system containers, rancher is source of truth, stop it. For user containers, do a no-op start to sync state.
addSyncAction(needsSynced, syncActions, ri, EVENT_START, checkOnly);
} else {
log.warn(UKNOWN_OUT_OF_SYNC_WARNING, ki.getUuid(), ri.getExternalId(), ki.getState(), ri.getState());
}
} else if (STATE_RUNNING.equals(ki.getState())) {
if (STATE_STOPPED.equals(ri.getState())) {
// Container is running in Rancher, but is not running on host.
addSyncAction(needsSynced, syncActions, ri, EVENT_STOP, checkOnly);
} else {
log.warn(UKNOWN_OUT_OF_SYNC_WARNING, ki.getUuid(), ri.getExternalId(), ki.getState(), ri.getState());
}
}
}
void addSyncAction(Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions, ReportedInstance ri, String action, boolean checkOnly) {
if (checkOnly) {
throw new ContainersOutOfSync();
}
needsSynced.put(ri.getExternalId(), ri);
syncActions.put(ri.getExternalId(), action);
}
void scheduleContainerEvent(Long agentId, Long hostId, ReportedInstance ri, String event) {
if (StringUtils.isEmpty(ri.getImage()) || StringUtils.isEmpty(ri.getExternalId()) || StringUtils.isEmpty(ri.getUuid())) {
log.error("Not enough information to schedule container event: [" + ri.toString() + "].");
return;
}
if (event.equals(scheduled.getIfPresent(ri.getExternalId()))) {
// Create container events only so often.
return;
} else {
scheduled.put(ri.getExternalId(), event);
}
ContainerEvent ce = objectManager.newRecord(ContainerEvent.class);
ce.setAccountId(agentId);
ce.setExternalFrom(ri.getImage());
ce.setExternalId(ri.getExternalId());
ce.setExternalStatus(event);
ce.setExternalTimestamp(ri.getCreated());
ce.setKind(CONTAINER_EVENT_KIND);
ce.setHostId(hostId);
Map<String, Object> data = new HashMap<String, Object>();
data.put(CONTAINER_EVENT_SYNC_NAME, ri.getUuid());
data.put(CONTAINER_EVENT_SYNC_LABELS, ri.getLabels());
ce = objectManager.create(ce);
processManager.scheduleStandardProcess(StandardProcess.CREATE, ce, data);
}
protected void forceStop(final String containerId, Long agentId) {
final Event event = new InstanceForceStop(containerId);
final RemoteAgent agent = agentLocator.lookupAgent(agentId);
agent.publish(event);
}
protected ReportedInstances getInstances(Ping ping) {
PingData data = ping.getData();
if (data == null || ping.getResourceId() == null) {
return null;
}
List<Map<String, Object>> resources = data.getResources();
if (resources == null || !ping.getOption(Ping.INSTANCES)) {
return null;
}
ReportedInstances reportedInstances = new ReportedInstances();
for (Map<String, Object> resource : resources) {
Object type = DataAccessor.fromMap(resource).withKey(ObjectMetaDataManager.TYPE_FIELD).as(String.class);
if (FIELD_HOST_UUID.equals(type))
reportedInstances.hostUuid = DataAccessor.fromMap(resource).withKey(ObjectMetaDataManager.UUID_FIELD).as(String.class);
if (!InstanceConstants.TYPE.equals(type))
continue;
ReportedInstance ri = new ReportedInstance(resource);
reportedInstances.byUuid.put(ri.getUuid(), ri);
reportedInstances.byExternalId.put(ri.getExternalId(), ri);
}
return reportedInstances;
}
protected class ContainersOutOfSync extends RuntimeException {
private static final long serialVersionUID = 1L;
}
protected AgentAndHost loadAgentAndHostData(ImmutablePair<Long, String> agentIdAndHostUuid) {
Long agentId = agentIdAndHostUuid.left;
String hostUuid = agentIdAndHostUuid.right;
Agent agent = objectManager.loadResource(Agent.class, agentId);
Host host = null;
Map<String, Host> hosts = null;
if (agent != null) {
hosts = agentDao.getHosts(agent.getId());
host = hosts.get(hostUuid);
}
if (agent == null || host == null)
throw new CantFindAgentAndHostException();
return new AgentAndHost(agent.getAccountId(), host.getId());
}
protected Map<String, KnownInstance> load(Long agentId) {
if (agentId == null) {
return new HashMap<String, KnownInstance>();
}
return monitorDao.getInstances(agentId.longValue());
}
private class AgentAndHost {
Long agentAccountId;
Long hostId;
AgentAndHost(Long agentAccountId, Long hostId) {
this.agentAccountId = agentAccountId;
this.hostId = hostId;
}
}
private class CantFindAgentAndHostException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
}
}
| code/iaas/ha/src/main/java/io/cattle/platform/ha/monitor/impl/PingInstancesMonitorImpl.java | package io.cattle.platform.ha.monitor.impl;
import static io.cattle.platform.core.constants.ContainerEventConstants.*;
import static io.cattle.platform.core.constants.HostConstants.*;
import static io.cattle.platform.core.constants.InstanceConstants.*;
import io.cattle.platform.agent.AgentLocator;
import io.cattle.platform.agent.RemoteAgent;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.AgentDao;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.ContainerEvent;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.eventing.model.Event;
import io.cattle.platform.framework.event.Ping;
import io.cattle.platform.framework.event.data.PingData;
import io.cattle.platform.ha.monitor.PingInstancesMonitor;
import io.cattle.platform.ha.monitor.dao.PingInstancesMonitorDao;
import io.cattle.platform.ha.monitor.event.InstanceForceStop;
import io.cattle.platform.ha.monitor.model.KnownInstance;
import io.cattle.platform.lock.LockDelegator;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.util.type.CollectionUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.netflix.config.DynamicLongProperty;
public class PingInstancesMonitorImpl implements PingInstancesMonitor {
private static final DynamicLongProperty CACHE_TIME = ArchaiusUtil.getLong("ha.instance.state.cache.millis");
private static final DynamicLongProperty HOST_ID_CACHE_TIME = ArchaiusUtil.getLong("ha.host.id.cache.millis");
private static final Logger log = LoggerFactory.getLogger(PingInstancesMonitorImpl.class);
private static final String UKNOWN_OUT_OF_SYNC_WARNING = "Instance out of sync and can't determine action to take. Uuid [{}]. Docker id [{}]. "
+ "State in rancher [{}]. State on host [{}]";
@Inject
AgentDao agentDao;
@Inject
ObjectMetaDataManager objectMetaDataManager;
@Inject
AgentLocator agentLocator;
@Inject
LockDelegator lockDelegator;
@Inject
PingInstancesMonitorDao monitorDao;
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager processManager;
Cache<String, Boolean> scheduled = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.MINUTES)
.build();
LoadingCache<Long, Map<String, KnownInstance>> instanceCache = CacheBuilder.newBuilder().expireAfterWrite(CACHE_TIME.get(), TimeUnit.MILLISECONDS)
.build(new CacheLoader<Long, Map<String, KnownInstance>>() {
@Override
public Map<String, KnownInstance> load(Long key) throws Exception {
return PingInstancesMonitorImpl.this.load(key);
}
});
LoadingCache<ImmutablePair<Long, String>, AgentAndHost> hostCache = CacheBuilder.newBuilder()
.expireAfterWrite(HOST_ID_CACHE_TIME.get(), TimeUnit.MILLISECONDS).build(new CacheLoader<ImmutablePair<Long, String>, AgentAndHost>() {
@Override
public AgentAndHost load(ImmutablePair<Long, String> key) throws Exception {
return PingInstancesMonitorImpl.this.loadAgentAndHostData(key);
}
});
@Override
public void pingReply(Ping ping) {
ReportedInstances reportedInstances = getInstances(ping);
if (reportedInstances == null || StringUtils.isEmpty(reportedInstances.hostUuid))
return;
long agentId = Long.parseLong(ping.getResourceId());
Map<String, KnownInstance> knownInstances = instanceCache.getUnchecked(agentId);
AgentAndHost agentAndHost = null;
try {
agentAndHost = hostCache.getUnchecked(new ImmutablePair<Long, String>(agentId, reportedInstances.hostUuid));
} catch (UncheckedExecutionException e) {
// CantFindAgentAndHostException can be ignored because the host may not exist yet. Rethrow all other exceptions.
if (!(e.getCause() instanceof CantFindAgentAndHostException)) {
throw e;
}
}
if (agentAndHost == null) {
log.info("Couldn't find host with uuid [{}] for agent [{}]", reportedInstances.hostUuid, agentId);
return;
}
try {
syncContainers(knownInstances, reportedInstances, agentAndHost.agentAccountId, agentId, agentAndHost.hostId, true);
} catch (ContainersOutOfSync e) {
knownInstances = load(agentId);
instanceCache.put(agentId, knownInstances);
syncContainers(knownInstances, reportedInstances, agentAndHost.agentAccountId, agentId, agentAndHost.hostId, false);
}
}
@Override
public void computeInstanceActivateReply(Event event) {
Long agentId = monitorDao.getAgentIdForInstanceHostMap(event.getResourceId());
if (agentId != null) {
instanceCache.invalidate(agentId);
}
}
/*
* If checkOnly is true, will raise a ContainersOutOfSync exception, indicating this should be reran with checkOnly set to false.
*/
void syncContainers(Map<String, KnownInstance> knownInstances, ReportedInstances reportedInstances, long agentAccountId, long agentId, long hostId,
boolean checkOnly) {
Map<String, ReportedInstance> needsSynced = new HashMap<String, ReportedInstance>();
Map<String, String> syncActions = new HashMap<String, String>();
determineSyncActions(knownInstances, reportedInstances, needsSynced, syncActions, checkOnly);
for (Map.Entry<String, ReportedInstance> syncEntry : needsSynced.entrySet()) {
ReportedInstance ri = syncEntry.getValue();
String syncAction = syncActions.get(syncEntry.getKey());
if (EVENT_INSTANCE_FORCE_STOP.equals(syncAction)) {
forceStop(ri.getExternalId(), agentId);
} else {
scheduleContainerEvent(agentAccountId, hostId, ri, syncAction);
}
}
}
void determineSyncActions(Map<String, KnownInstance> knownInstances, ReportedInstances reportedInstances, Map<String, ReportedInstance> needsSynced,
Map<String, String> syncActions, boolean checkOnly) {
Map<String, KnownInstance> inRancher = new HashMap<String, KnownInstance>(knownInstances);
Map<String, ReportedInstance> onHost = new HashMap<String, ReportedInstance>(reportedInstances.byExternalId);
for (Map.Entry<String, ReportedInstance> reported : reportedInstances.byUuid.entrySet()) {
KnownInstance ki = knownInstances.get(reported.getKey());
if (ki != null) {
removeAndDetermineSyncAction(needsSynced, syncActions, checkOnly, inRancher, onHost, reported.getValue(), ki,
reported.getValue().getExternalId(), reported.getKey());
}
}
if (!onHost.isEmpty() || !inRancher.isEmpty()) {
Map<String, KnownInstance> knownByExternalId = new HashMap<String, KnownInstance>();
for (KnownInstance ki : knownInstances.values()) {
if (StringUtils.isNotEmpty(ki.getExternalId()))
knownByExternalId.put(ki.getExternalId(), ki);
}
for (Map.Entry<String, ReportedInstance> reported : reportedInstances.byExternalId.entrySet()) {
KnownInstance ki = knownByExternalId.get(reported.getKey());
if (ki != null) {
removeAndDetermineSyncAction(needsSynced, syncActions, checkOnly, inRancher, onHost, reported.getValue(), ki,
reported.getKey(), ki.getUuid());
}
}
}
// Anything left in onHost is on the host, but not in rancher.
for (Map.Entry<String, ReportedInstance> create : onHost.entrySet()) {
ReportedInstance ri = create.getValue();
addSyncAction(needsSynced, syncActions, ri, EVENT_START, checkOnly);
}
// Anything left in inRancher is in rancher, but not on the host.
for (KnownInstance ki : inRancher.values()) {
List<String> forRemove = Arrays.asList(CommonStatesConstants.REMOVING, InstanceConstants.STATE_ERROR,
InstanceConstants.STATE_ERRORING);
if (objectMetaDataManager.isTransitioningState(Instance.class, ki.getState()) || ki.getRemoved() != null
|| forRemove.contains(ki.getState())
|| (STATE_STOPPED.equals(ki.getState()) && StringUtils.isEmpty(ki.getExternalId())))
continue;
ReportedInstance ri = new ReportedInstance();
ri.setExternalId(ki.getExternalId());
ri.setUuid(ki.getUuid());
Object imageUuid = CollectionUtils.getNestedValue(ki.getData(), DataUtils.FIELDS, FIELD_IMAGE_UUID);
String image = imageUuid != null ? imageUuid.toString() : null;
ri.setImage(image);
addSyncAction(needsSynced, syncActions, ri, EVENT_DESTROY, checkOnly);
}
}
void removeAndDetermineSyncAction(Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions, boolean checkOnly,
Map<String, KnownInstance> inRancher, Map<String, ReportedInstance> onHost, ReportedInstance reportedInstance, KnownInstance instance,
String onHostKey, String inRancherKey) {
onHost.remove(onHostKey);
inRancher.remove(inRancherKey);
reportedInstance.setInstance(instance);
determineSyncAction(instance, reportedInstance, needsSynced, syncActions, checkOnly);
}
void determineSyncAction(KnownInstance ki, ReportedInstance ri, Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions,
boolean checkOnly) {
if (objectMetaDataManager.isTransitioningState(Instance.class, ki.getState()) || StringUtils.equals(ki.getState(), ri.getState()))
return;
if (STATE_RUNNING.equals(ri.getState())) {
// Container is running on host but not in Rancher. Take action
if (ki.getRemoved() != null) {
// If rancher thinks it's removed, send an explicit stop down to host.
addSyncAction(needsSynced, syncActions, ri, EVENT_INSTANCE_FORCE_STOP, checkOnly);
} else if (STATE_STOPPED.equals(ki.getState())) {
// For system containers, rancher is source of truth, stop it. For user containers, do a no-op start to sync state.
addSyncAction(needsSynced, syncActions, ri, EVENT_START, checkOnly);
} else {
log.warn(UKNOWN_OUT_OF_SYNC_WARNING, ki.getUuid(), ri.getExternalId(), ki.getState(), ri.getState());
}
} else if (STATE_RUNNING.equals(ki.getState())) {
if (STATE_STOPPED.equals(ri.getState())) {
// Container is running in Rancher, but is not running on host.
addSyncAction(needsSynced, syncActions, ri, EVENT_STOP, checkOnly);
} else {
log.warn(UKNOWN_OUT_OF_SYNC_WARNING, ki.getUuid(), ri.getExternalId(), ki.getState(), ri.getState());
}
}
}
void addSyncAction(Map<String, ReportedInstance> needsSynced, Map<String, String> syncActions, ReportedInstance ri, String action, boolean checkOnly) {
if (checkOnly) {
throw new ContainersOutOfSync();
}
needsSynced.put(ri.getExternalId(), ri);
syncActions.put(ri.getExternalId(), action);
}
void scheduleContainerEvent(Long agentId, Long hostId, ReportedInstance ri, String event) {
if (StringUtils.isEmpty(ri.getImage()) || StringUtils.isEmpty(ri.getExternalId()) || StringUtils.isEmpty(ri.getUuid())) {
log.error("Not enough information to schedule container event: [" + ri.toString() + "].");
return;
}
if (scheduled.getIfPresent(ri.getExternalId()) == null) {
scheduled.put(ri.getExternalId(), true);
} else {
// Create container events only so often.
return;
}
ContainerEvent ce = objectManager.newRecord(ContainerEvent.class);
ce.setAccountId(agentId);
ce.setExternalFrom(ri.getImage());
ce.setExternalId(ri.getExternalId());
ce.setExternalStatus(event);
ce.setExternalTimestamp(ri.getCreated());
ce.setKind(CONTAINER_EVENT_KIND);
ce.setHostId(hostId);
Map<String, Object> data = new HashMap<String, Object>();
data.put(CONTAINER_EVENT_SYNC_NAME, ri.getUuid());
data.put(CONTAINER_EVENT_SYNC_LABELS, ri.getLabels());
ce = objectManager.create(ce);
processManager.scheduleStandardProcess(StandardProcess.CREATE, ce, data);
}
protected void forceStop(final String containerId, Long agentId) {
final Event event = new InstanceForceStop(containerId);
final RemoteAgent agent = agentLocator.lookupAgent(agentId);
agent.publish(event);
}
protected ReportedInstances getInstances(Ping ping) {
PingData data = ping.getData();
if (data == null || ping.getResourceId() == null) {
return null;
}
List<Map<String, Object>> resources = data.getResources();
if (resources == null || !ping.getOption(Ping.INSTANCES)) {
return null;
}
ReportedInstances reportedInstances = new ReportedInstances();
for (Map<String, Object> resource : resources) {
Object type = DataAccessor.fromMap(resource).withKey(ObjectMetaDataManager.TYPE_FIELD).as(String.class);
if (FIELD_HOST_UUID.equals(type))
reportedInstances.hostUuid = DataAccessor.fromMap(resource).withKey(ObjectMetaDataManager.UUID_FIELD).as(String.class);
if (!InstanceConstants.TYPE.equals(type))
continue;
ReportedInstance ri = new ReportedInstance(resource);
reportedInstances.byUuid.put(ri.getUuid(), ri);
reportedInstances.byExternalId.put(ri.getExternalId(), ri);
}
return reportedInstances;
}
protected class ContainersOutOfSync extends RuntimeException {
private static final long serialVersionUID = 1L;
}
protected AgentAndHost loadAgentAndHostData(ImmutablePair<Long, String> agentIdAndHostUuid) {
Long agentId = agentIdAndHostUuid.left;
String hostUuid = agentIdAndHostUuid.right;
Agent agent = objectManager.loadResource(Agent.class, agentId);
Host host = null;
Map<String, Host> hosts = null;
if (agent != null) {
hosts = agentDao.getHosts(agent.getId());
host = hosts.get(hostUuid);
}
if (agent == null || host == null)
throw new CantFindAgentAndHostException();
return new AgentAndHost(agent.getAccountId(), host.getId());
}
protected Map<String, KnownInstance> load(Long agentId) {
if (agentId == null) {
return new HashMap<String, KnownInstance>();
}
return monitorDao.getInstances(agentId.longValue());
}
private class AgentAndHost {
Long agentAccountId;
Long hostId;
AgentAndHost(Long agentAccountId, Long hostId) {
this.agentAccountId = agentAccountId;
this.hostId = hostId;
}
}
private class CantFindAgentAndHostException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
}
}
| Send containers events when the event changes value
| code/iaas/ha/src/main/java/io/cattle/platform/ha/monitor/impl/PingInstancesMonitorImpl.java | Send containers events when the event changes value | <ide><path>ode/iaas/ha/src/main/java/io/cattle/platform/ha/monitor/impl/PingInstancesMonitorImpl.java
<ide> ObjectManager objectManager;
<ide> @Inject
<ide> ObjectProcessManager processManager;
<del> Cache<String, Boolean> scheduled = CacheBuilder.newBuilder()
<add> Cache<String, String> scheduled = CacheBuilder.newBuilder()
<ide> .expireAfterWrite(15, TimeUnit.MINUTES)
<ide> .build();
<ide>
<ide> return;
<ide> }
<ide>
<del> if (scheduled.getIfPresent(ri.getExternalId()) == null) {
<del> scheduled.put(ri.getExternalId(), true);
<add> if (event.equals(scheduled.getIfPresent(ri.getExternalId()))) {
<add> // Create container events only so often.
<add> return;
<ide> } else {
<del> // Create container events only so often.
<del> return;
<add> scheduled.put(ri.getExternalId(), event);
<ide> }
<ide> ContainerEvent ce = objectManager.newRecord(ContainerEvent.class);
<ide> ce.setAccountId(agentId); |
|
Java | agpl-3.0 | f67d468448833d57d2fb9e7f747a966959d14335 | 0 | lisaslyis/aikuma,aikuma/aikuma,hleeldc/aikuma,aikuma/aikuma,lisaslyis/aikuma,aikuma/aikuma,lisaslyis/aikuma,lisaslyis/aikuma,hleeldc/aikuma,lisaslyis/aikuma,hleeldc/aikuma,aikuma/aikuma,aikuma/aikuma,hleeldc/aikuma,hleeldc/aikuma | package org.lp20.aikuma.storage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import static org.lp20.aikuma.storage.Utils.gapi_connect;
/**
* Implementation of DataStore backed by Google Drive.
*
* @author haejoong
*/
public class GoogleDriveStorage implements DataStore {
String accessToken_;
/**
* GoogleDriveStorage allows saving and retrieving data to and from the
* Google Drive. It requires an access token for the scopes specified by
* the {@code getScopes()} method. The access token can be obtained in
* different ways. The following example uses GoogleAuth class.
*
* {@code
* GoogleAuth auth = new GoogleAuth(myClientId, myClientSecret);
* String authCode = get_auth_code_for_scopes(GoogleDriveStorage.getScopes());
* auth.requestAccessToken(authCode);
* GoogleDriveStorage gd = new GoogleDriveStorage(auth.getAccessToken());
* }
*
* @param accessToken
*/
public GoogleDriveStorage(String accessToken) {
accessToken_ = accessToken;
}
@Override
public InputStream load(String identifier) {
String query = "trashed = false and title = \"" + identifier + "\"";
JSONObject obj = gapi_list_files(query, null);
JSONArray arr = (JSONArray) obj.get("items");
if (arr.size() == 0)
return null;
JSONObject item = (JSONObject) arr.get(0);
String url = (String) item.get("downloadUrl");
return gapi_download(url);
}
@Override
public String store(String identifier, Data data) {
// identifier - aikuma file path
JSONObject obj = gapi_insert(data);
if (obj == null)
return null;
JSONObject meta = new JSONObject();
meta.put("title", identifier);
String fileid = (String) obj.get("id");
JSONObject obj2 = gapi_update_metadata(fileid, meta);
if (obj2 != null)
return (String) obj2.get("webContentLink");
else
return null;
}
@Override
public boolean share(String identifier) {
String name = "\"" + identifier.replaceAll("\"", "\\\"") + "\"";
JSONObject obj = gapi_list_files("trashed = false and title = " + name, null);
if (obj == null)
return false; // "list" call failed
String kind = (String) obj.get("kind");
String fileid = null;
if (kind.equals("drive#fileList")) {
JSONArray arr = (JSONArray) obj.get("items");
if (arr != null && arr.size() > 0) {
JSONObject o = (JSONObject) arr.get(0);
fileid = (String) o.get("id");
}
}
if (fileid == null)
return false; // unexpected response type
JSONObject r = gapi_make_public(fileid);
if (r != null)
return true;
else
return false;
}
@Override
public void list(ListItemHandler listItemHandler) {
JSONObject obj = gapi_list_files("trashed = false", null);
while (obj != null) {
JSONArray arr = (JSONArray) obj.get("items");
for (Object item: arr) {
JSONObject o = (JSONObject) item;
String identifier = (String) o.get("title");
String datestr = (String) o.get("modifiedDate");
SimpleDateFormat datefmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date;
try {
date = datefmt.parse(datestr);
}
catch (ParseException e) {
date = null;
}
boolean cont = listItemHandler.processItem(identifier, date);
if (cont == false)
return;
}
String nextPageToken = (String) obj.get("nextPageToken");
if (nextPageToken != null)
obj = gapi_list_files(null, nextPageToken);
else
obj = null;
}
}
/**
* Returns a list of api scopes required to access files.
*
* @return List of scopes.
*/
public static List<String> getScopes() {
ArrayList<String> apis = new ArrayList<String>();
apis.add("https://www.googleapis.com/auth/drive.file");
return apis;
}
/**
* Upload a file.
* @param data
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_insert(Data data) {
try {
URL url = new URL("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
HttpURLConnection con = gapi_connect(url, "POST", accessToken_);
con.setRequestProperty("Content-Type", data.getMimeType());
con.setChunkedStreamingMode(8192);
Utils.copyStream(data.getInputStream(), con.getOutputStream(), false);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* Update metadata of an existing file.
* @param fileid
* @param obj
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_update_metadata(String fileid, JSONObject obj) {
try {
String metajson = obj.toJSONString();
URL url = new URL("https://www.googleapis.com/drive/v2/files/" + fileid);
HttpURLConnection con = gapi_connect(url, "PUT", accessToken_);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", String.valueOf(metajson.length()));
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(metajson);
writer.flush();
writer.close();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* List files.
* @param searchQuery
* @param pageToken
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_list_files(String searchQuery, String pageToken) {
try {
String base = "https://www.googleapis.com/drive/v2/files/";
Utils.UrlBuilder ub = new Utils.UrlBuilder(base);
if (pageToken != null && !pageToken.isEmpty())
ub.addQuery("pageToken", pageToken);
else if (searchQuery != null && !searchQuery.isEmpty())
ub.addQuery("q", searchQuery);
HttpURLConnection con = gapi_connect(ub.toUrl(), "GET", accessToken_);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* Download a file.
* @param url
* @return InputStream if successful, null otherwise.
*/
private InputStream gapi_download(String url) {
try {
HttpURLConnection con = gapi_connect(new URL(url), "GET", accessToken_);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
return con.getInputStream();
}
catch (IOException e) {
return null;
}
}
/**
* Make a file public.
* @param fileid String file id.
* @return json response from the server.
*/
private JSONObject gapi_make_public(String fileid)
{
try {
JSONObject meta = new JSONObject();
meta.put("type", "anyone");
meta.put("role", "reader");
String metajson = meta.toJSONString();
URL url = new URL("https://www.googleapis.com/drive/v2/files/" + fileid + "/permissions");
HttpURLConnection con = gapi_connect(url, "POST", accessToken_);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", String.valueOf(metajson.length()));
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(metajson);
writer.flush();
writer.close();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
System.out.println("exception");
return null;
}
}
}
| AikumaCloudStorage/src/org/lp20/aikuma/storage/GoogleDriveStorage.java | package org.lp20.aikuma.storage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import static org.lp20.aikuma.storage.Utils.gapi_connect;
/**
* Implementation of DataStore backed by Google Drive.
*
* @author haejoong
*/
public class GoogleDriveStorage implements DataStore {
String accessToken_;
/**
* GoogleDriveStorage allows saving and retrieving data to and from the
* Google Drive. It requires an access token for the scopes specified by
* the {@code getScopes()} method. The access token can be obtained in
* different ways. The following example uses GoogleAuth class.
*
* {@code
* GoogleAuth auth = new GoogleAuth(myClientId, myClientSecret);
* String authCode = get_auth_code_for_scopes(GoogleDriveStorage.getScopes());
* auth.requestAccessToken(authCode);
* GoogleDriveStorage gd = new GoogleDriveStorage(auth.getAccessToken());
* }
*
* @param accessToken
*/
public GoogleDriveStorage(String accessToken) {
accessToken_ = accessToken;
}
@Override
public InputStream load(String identifier) {
String query = "trashed = false and title = \"" + identifier + "\"";
JSONObject obj = gapi_list_files(query, null);
JSONArray arr = (JSONArray) obj.get("items");
if (arr.size() == 0)
return null;
JSONObject item = (JSONObject) arr.get(0);
String url = (String) item.get("downloadUrl");
return gapi_download(url);
}
@Override
public String store(String identifier, Data data) {
// identifier - aikuma file path
JSONObject obj = gapi_insert(data);
if (obj == null)
return null;
JSONObject meta = new JSONObject();
meta.put("title", identifier);
String fileid = (String) obj.get("id");
JSONObject obj2 = gapi_update_metadata(fileid, meta);
if (obj2 != null)
return (String) obj2.get("webContentLink");
else
return null;
}
@Override
public boolean share(String identifier) {
String name = "\"" + identifier.replaceAll("\"", "\\\"") + "\"";
JSONObject obj = gapi_list_files("trashed = false and title = " + name, null);
if (obj == null)
return false;
JSONArray arr = (JSONArray) obj.get("items");
if (arr != null && arr.size() > 0) {
JSONObject o = (JSONObject) arr.get(0);
String fileid = (String) o.get("id");
JSONObject r = gapi_make_public(fileid);
return (r != null);
}
return false;
}
@Override
public void list(ListItemHandler listItemHandler) {
JSONObject obj = gapi_list_files("trashed = false", null);
while (obj != null) {
JSONArray arr = (JSONArray) obj.get("items");
for (Object item: arr) {
JSONObject o = (JSONObject) item;
String identifier = (String) o.get("title");
String datestr = (String) o.get("modifiedDate");
SimpleDateFormat datefmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date;
try {
date = datefmt.parse(datestr);
}
catch (ParseException e) {
date = null;
}
boolean cont = listItemHandler.processItem(identifier, date);
if (cont == false)
return;
}
String nextPageToken = (String) obj.get("nextPageToken");
if (nextPageToken != null)
obj = gapi_list_files(null, nextPageToken);
else
obj = null;
}
}
/**
* Returns a list of api scopes required to access files.
*
* @return List of scopes.
*/
public static List<String> getScopes() {
ArrayList<String> apis = new ArrayList<String>();
apis.add("https://www.googleapis.com/auth/drive.file");
return apis;
}
/**
* Upload a file.
* @param data
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_insert(Data data) {
try {
URL url = new URL("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
HttpURLConnection con = gapi_connect(url, "POST", accessToken_);
con.setRequestProperty("Content-Type", data.getMimeType());
con.setChunkedStreamingMode(8192);
Utils.copyStream(data.getInputStream(), con.getOutputStream(), false);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* Update metadata of an existing file.
* @param fileid
* @param obj
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_update_metadata(String fileid, JSONObject obj) {
try {
String metajson = obj.toJSONString();
URL url = new URL("https://www.googleapis.com/drive/v2/files/" + fileid);
HttpURLConnection con = gapi_connect(url, "PUT", accessToken_);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", String.valueOf(metajson.length()));
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(metajson);
writer.flush();
writer.close();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* List files.
* @param searchQuery
* @param pageToken
* @return JSONObject if successful, null otherwise.
*/
private JSONObject gapi_list_files(String searchQuery, String pageToken) {
try {
String base = "https://www.googleapis.com/drive/v2/files/";
Utils.UrlBuilder ub = new Utils.UrlBuilder(base);
if (pageToken != null && !pageToken.isEmpty())
ub.addQuery("pageToken", pageToken);
else if (searchQuery != null && !searchQuery.isEmpty())
ub.addQuery("q", searchQuery);
HttpURLConnection con = gapi_connect(ub.toUrl(), "GET", accessToken_);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
return null;
}
}
/**
* Download a file.
* @param url
* @return InputStream if successful, null otherwise.
*/
private InputStream gapi_download(String url) {
try {
HttpURLConnection con = gapi_connect(new URL(url), "GET", accessToken_);
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
return con.getInputStream();
}
catch (IOException e) {
return null;
}
}
/**
* Make a file public.
* @param fileid String file id.
* @return json response from the server.
*/
private JSONObject gapi_make_public(String fileid)
{
try {
JSONObject meta = new JSONObject();
meta.put("type", "anyone");
meta.put("role", "reader");
String metajson = meta.toJSONString();
URL url = new URL("https://www.googleapis.com/drive/v2/files/" + fileid + "/permissions");
HttpURLConnection con = gapi_connect(url, "POST", accessToken_);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", String.valueOf(metajson.length()));
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(metajson);
writer.flush();
writer.close();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
String json = Utils.readStream(con.getInputStream());
return (JSONObject) JSONValue.parse(json);
}
catch (IOException e) {
System.out.println("exception");
return null;
}
}
}
| more error checking
| AikumaCloudStorage/src/org/lp20/aikuma/storage/GoogleDriveStorage.java | more error checking | <ide><path>ikumaCloudStorage/src/org/lp20/aikuma/storage/GoogleDriveStorage.java
<ide> public boolean share(String identifier) {
<ide> String name = "\"" + identifier.replaceAll("\"", "\\\"") + "\"";
<ide> JSONObject obj = gapi_list_files("trashed = false and title = " + name, null);
<add>
<ide> if (obj == null)
<add> return false; // "list" call failed
<add>
<add> String kind = (String) obj.get("kind");
<add> String fileid = null;
<add> if (kind.equals("drive#fileList")) {
<add> JSONArray arr = (JSONArray) obj.get("items");
<add> if (arr != null && arr.size() > 0) {
<add> JSONObject o = (JSONObject) arr.get(0);
<add> fileid = (String) o.get("id");
<add> }
<add> }
<add>
<add> if (fileid == null)
<add> return false; // unexpected response type
<add>
<add> JSONObject r = gapi_make_public(fileid);
<add> if (r != null)
<add> return true;
<add> else
<ide> return false;
<del> JSONArray arr = (JSONArray) obj.get("items");
<del> if (arr != null && arr.size() > 0) {
<del> JSONObject o = (JSONObject) arr.get(0);
<del> String fileid = (String) o.get("id");
<del> JSONObject r = gapi_make_public(fileid);
<del> return (r != null);
<del> }
<del> return false;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 801ffbc967c2c73ce1c10fb2c538b9c8a1970eab | 0 | hgl888/android-maven-plugin,mitchhentges/android-maven-plugin,b-cuts/android-maven-plugin,xieningtao/android-maven-plugin,jdegroot/android-maven-plugin,mitchhentges/android-maven-plugin,wskplho/android-maven-plugin,ashutoshbhide/android-maven-plugin,jdegroot/android-maven-plugin,xiaojiaqiao/android-maven-plugin,Cha0sX/android-maven-plugin,kedzie/maven-android-plugin,psorobka/android-maven-plugin,hgl888/android-maven-plugin,wskplho/android-maven-plugin,Stuey86/android-maven-plugin,ashutoshbhide/android-maven-plugin,Cha0sX/android-maven-plugin,WonderCsabo/maven-android-plugin,kevinsawicki/maven-android-plugin,CJstar/android-maven-plugin,CJstar/android-maven-plugin,WonderCsabo/maven-android-plugin,simpligility/android-maven-plugin,xiaojiaqiao/android-maven-plugin,greek1979/maven-android-plugin,xieningtao/android-maven-plugin,secondsun/maven-android-plugin,repanda/android-maven-plugin,psorobka/android-maven-plugin,xiaojiaqiao/android-maven-plugin,Cha0sX/android-maven-plugin,b-cuts/android-maven-plugin,kedzie/maven-android-plugin,secondsun/maven-android-plugin,Stuey86/android-maven-plugin,greek1979/maven-android-plugin,secondsun/maven-android-plugin,repanda/android-maven-plugin | /*
* Copyright (C) 2009 Jayway AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.maven.plugins.android;
import org.codehaus.plexus.util.ReflectionUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Excercises the {@link AndroidSdk} class.
*
* @author [email protected]
* @author Manfred Moser <[email protected]>
*/
public class AndroidSdkTest {
private SdkTestSupport sdkTestSupport;
@Before
public void setUp(){
sdkTestSupport = new SdkTestSupport();
}
@Test
public void givenToolAdbThenPathIsCommon() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("adb");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/tools/adb", pathForTool);
}
@Test
public void givenToolAndroidThenPathIsCommon() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("android");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/tools/android", pathForTool);
}
@Test
public void givenToolAaptAndPlatform1dot1ThenPathIsPlatform1dot1() {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-2/tools/aapt"), new File(pathForTool));
}
@Test
public void givenToolAaptAndPlatform1dot5ThenPathIsPlatform1dot5() {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-3/tools/aapt"), new File(pathForTool));
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidSdkPathThenException() throws IOException {
new AndroidSdk(File.createTempFile("maven-android-plugin", "test"), null).getLayout();
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidPlatformStringThenException() throws IOException {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalidplatform");
}
@Test
public void givenSdk15PathThenLayoutIs15(){
Assert.assertEquals(sdkTestSupport.getSdk_with_platform_default().getLayout(), AndroidSdk.Layout.LAYOUT_1_5);
}
@Test
public void givenPlatform1dot5ThenPlatformis1dot5() throws IllegalAccessException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_1_5());
Assert.assertEquals(new File(path, "/platforms/android-3"),sdkTestSupport.getSdk_with_platform_1_5().getPlatform());
}
@Test
public void givenPlatformNullThenPlatformisSomethingValidLooking() throws IllegalAccessException, URISyntaxException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_default());
final File platform = sdkTestSupport.getSdk_with_platform_default().getPlatform();
final String platformPath = platform.getAbsolutePath();
final String pathPath = path.getAbsolutePath();
final String regex = new File(pathPath + "/platforms/android-.*").toURI().toString();
Assert.assertTrue(new File(platformPath).toURI().toString().matches(regex));
}
/**
* Test all available platforms and api level versions. All have to be installed locally
* for this test to pass including the obsolete ones.
*/
@Test
public void validPlatformsAndApiLevels() {
final AndroidSdk sdk2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2");
final AndroidSdk sdk3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final AndroidSdk sdk4 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4");
final AndroidSdk sdk5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "5");
final AndroidSdk sdk6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "6");
final AndroidSdk sdk7 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "7");
final AndroidSdk sdk8 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "8");
final AndroidSdk sdk1_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.1");
final AndroidSdk sdk1_5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.5");
final AndroidSdk sdk1_6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.6");
final AndroidSdk sdk2_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.0");
final AndroidSdk sdk2_0_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.0.1");
final AndroidSdk sdk2_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.1");
final AndroidSdk sdk2_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.2");
}
@Test(expected = InvalidSdkException.class)
public void invalidPlatformAndApiLevels() {
final AndroidSdk invalid = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalid");
}
}
| src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java | /*
* Copyright (C) 2009 Jayway AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.maven.plugins.android;
import org.codehaus.plexus.util.ReflectionUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* Excercises the {@link AndroidSdk} class.
*
* @author [email protected]
* @author Manfred Moser <[email protected]>
*/
public class AndroidSdkTest {
private SdkTestSupport sdkTestSupport;
@Before
public void setUp(){
sdkTestSupport = new SdkTestSupport();
}
@Test
public void givenToolAdbThenPathIsCommon() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("adb");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/tools/adb", pathForTool);
}
@Test
public void givenToolAndroidThenPathIsCommon() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("android");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/tools/android", pathForTool);
}
@Test
public void givenToolAaptAndPlatform1dot1ThenPathIsPlatform1dot1() {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-2/tools/aapt", pathForTool);
}
@Test
public void givenToolAaptAndPlatform1dot5ThenPathIsPlatform1dot5() {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-3/tools/aapt", pathForTool);
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidSdkPathThenException() throws IOException {
new AndroidSdk(File.createTempFile("maven-android-plugin", "test"), null).getLayout();
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidPlatformStringThenException() throws IOException {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalidplatform");
}
@Test
public void givenSdk15PathThenLayoutIs15(){
Assert.assertEquals(sdkTestSupport.getSdk_with_platform_default().getLayout(), AndroidSdk.Layout.LAYOUT_1_5);
}
@Test
public void givenPlatform1dot5ThenPlatformis1dot5() throws IllegalAccessException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_1_5());
Assert.assertEquals(new File(path, "/platforms/android-3"),sdkTestSupport.getSdk_with_platform_1_5().getPlatform());
}
@Test
public void givenPlatformNullThenPlatformisSomethingValidLooking() throws IllegalAccessException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_default());
final File platform = sdkTestSupport.getSdk_with_platform_default().getPlatform();
final String platformPath = platform.getAbsolutePath();
final String pathPath = path.getAbsolutePath();
final String regex = pathPath + "/platforms/android-.*";
Assert.assertTrue(platformPath.matches(regex));
}
/**
* Test all available platforms and api level versions. All have to be installed locally
* for this test to pass including the obsolete ones.
*/
@Test
public void validPlatformsAndApiLevels() {
final AndroidSdk sdk2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2");
final AndroidSdk sdk3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final AndroidSdk sdk4 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4");
final AndroidSdk sdk5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "5");
final AndroidSdk sdk6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "6");
final AndroidSdk sdk7 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "7");
final AndroidSdk sdk8 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "8");
final AndroidSdk sdk1_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.1");
final AndroidSdk sdk1_5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.5");
final AndroidSdk sdk1_6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.6");
final AndroidSdk sdk2_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.0");
final AndroidSdk sdk2_0_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.0.1");
final AndroidSdk sdk2_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.1");
final AndroidSdk sdk2_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.2");
}
@Test(expected = InvalidSdkException.class)
public void invalidPlatformAndApiLevels() {
final AndroidSdk invalid = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalid");
}
}
| Make tests windows-compatible.
| src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java | Make tests windows-compatible. | <ide><path>rc/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<ide>
<ide> /**
<ide> * Excercises the {@link AndroidSdk} class.
<ide> public void givenToolAaptAndPlatform1dot1ThenPathIsPlatform1dot1() {
<ide> final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2");
<ide> final String pathForTool = sdk.getPathForTool("aapt");
<del> Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-2/tools/aapt", pathForTool);
<add> Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-2/tools/aapt"), new File(pathForTool));
<ide> }
<ide>
<ide> @Test
<ide> public void givenToolAaptAndPlatform1dot5ThenPathIsPlatform1dot5() {
<ide> final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
<ide> final String pathForTool = sdk.getPathForTool("aapt");
<del> Assert.assertEquals(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-3/tools/aapt", pathForTool);
<add> Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platforms/android-3/tools/aapt"), new File(pathForTool));
<ide> }
<ide>
<ide> @Test(expected = InvalidSdkException.class)
<ide> }
<ide>
<ide> @Test
<del> public void givenPlatformNullThenPlatformisSomethingValidLooking() throws IllegalAccessException {
<add> public void givenPlatformNullThenPlatformisSomethingValidLooking() throws IllegalAccessException, URISyntaxException {
<ide> final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_default());
<ide> final File platform = sdkTestSupport.getSdk_with_platform_default().getPlatform();
<ide> final String platformPath = platform.getAbsolutePath();
<ide> final String pathPath = path.getAbsolutePath();
<del> final String regex = pathPath + "/platforms/android-.*";
<del> Assert.assertTrue(platformPath.matches(regex));
<add> final String regex = new File(pathPath + "/platforms/android-.*").toURI().toString();
<add> Assert.assertTrue(new File(platformPath).toURI().toString().matches(regex));
<ide> }
<ide>
<ide> /** |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.